<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Animesh on Medium]]></title>
        <description><![CDATA[Stories by Animesh on Medium]]></description>
        <link>https://medium.com/@droiddev5911?source=rss-5caf11458b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XOieAHv8W0vKrDPutgyYgg.jpeg</url>
            <title>Stories by Animesh on Medium</title>
            <link>https://medium.com/@droiddev5911?source=rss-5caf11458b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:22:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@droiddev5911/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why EditText Automatically Restores Its Text but ImageView Loses Its Image During Configuration…]]></title>
            <link>https://medium.com/@droiddev5911/why-edittext-automatically-restores-its-text-but-imageview-loses-its-image-during-configuration-0a6e86b8a64e?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a6e86b8a64e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 15:18:00 GMT</pubDate>
            <atom:updated>2026-03-31T15:18:00.087Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why EditText Automatically Restores Its Text but ImageView Loses Its Image During Configuration Changes in Android?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8svrR9v7t2obvPNc-GN5gg.png" /></figure><p>If you’ve ever tested your Android app in dark mode or rotated the screen, you might have noticed something interesting:</p><ul><li>The text inside an <strong>EditText</strong> stays there.</li><li>But an image you selected into an <strong>ImageView</strong> suddenly disappears.</li></ul><p>At first glance, this feels inconsistent. Why does Android preserve one but not the other?</p><p>Understanding this behavior requires a deeper look into <strong>configuration changes</strong> and how Android saves and restores view state.</p><h3>What Is a Configuration Change?</h3><p>A configuration change occurs when device settings that affect resources change. Common examples include:</p><ul><li>Switching between light and dark mode</li><li>Rotating the screen (portrait to landscape)</li><li>Changing language or font size</li></ul><p>When this happens, Android <strong>destroys and recreates the Activity</strong> so it can reload the correct resources (such as values-night for dark mode).</p><p>This means your UI is rebuilt from scratch unless <strong>Android</strong> or <strong>you</strong> save its state.</p><h4>How Android Automatically Saves EditText State</h4><p>Android provides a built-in mechanism called <strong>View State Saving</strong>. When an Activity is about to be destroyed, the system saves the state of all views that:</p><ul><li>Have an android:id</li><li>Have state saving enabled</li></ul><p>EditText is designed to save:</p><ul><li>The text entered by the user</li><li>Cursor position</li><li>Selection range</li></ul><p>So when the Activity is recreated, Android automatically restores the text without any extra code from the developer.</p><p>That’s why your typed text is still there after rotation or theme change.</p><h4>Why ImageView Does Not Restore Images Automatically?</h4><p>Now let’s talk about ImageView. When you set an image dynamically:</p><pre>imgProfile.setImageURI(uri)</pre><p>Android <strong>does not</strong> automatically save this image. The reason is mainly <strong>performance and memory safety</strong>.</p><p>Images can be:</p><ul><li>Large in size</li><li>Loaded from external storage or network</li><li>Expensive to serialize into a Bundle</li></ul><p>If Android tried to save every bitmap automatically, configuration changes could:</p><ul><li>Become slow</li><li>Cause memory issues</li><li>Even crash the app with TransactionTooLargeException</li></ul><p>So the framework intentionally avoids saving image content automatically.</p><h4>What Actually Gets Saved During a Configuration Change</h4><p>When a configuration change occurs, Android does something like this internally:</p><ol><li>Calls onSaveInstanceState() on the Activity.</li><li>Saves the state of each view into a Bundle.</li><li>Destroys the Activity.</li><li>Recreates the Activity.</li><li>Restores view state from the Bundle.</li></ol><p>Lightweight data like text and booleans are safe to store. Large binary data like images is not.</p><h4>How to Properly Preserve an Image in ImageView</h4><p>To keep the selected image across configuration changes, you should save the image <strong>URI</strong>, not the bitmap.</p><p><strong>But wait a min, you might have question like URI is not bitmap, it’s a address why can’t android saves it on it’s own like it did for EditText or other views? URI is just a lightweight string-like reference, not a heavy bitmap.</strong></p><p>Even though a <strong>URI is small</strong>, Android still does <strong>not</strong> save it automatically because <strong>ImageView does not own the URI, </strong>it only owns the <strong>Drawable</strong>.</p><p>When you do: imgProfile.setImageURI(uri)</p><p>internally ImageView:</p><ol><li>Resolves the URI</li><li>Loads a drawable/bitmap</li><li>Displays it</li><li><strong>Discards the original URI</strong></li></ol><p>So from Android’s perspective: ImageView state is Drawable NOT the URI. And Android cannot serialize a Drawable safely across configuration changes.</p><h4>Real Risk: URI May Become Invalid</h4><p>Imagine this flow:</p><pre>User picks image from Google Photos<br>URI = content://com.google.android.apps.photos/…</pre><p>After configuration change:</p><ul><li>That content provider might revoke access</li><li>Temporary URI permissions might be gone</li><li>The image might no longer be accessible</li></ul><p>If Android restored the URI automatically and it failed, your app would crash or show inconsistent UI.</p><p>So the framework leaves the responsibility to the developer to:</p><ul><li>decide whether the URI should persist</li><li>and how long it should remain valid</li></ul><p>Android does not automatically save ImageView URIs not because they are large, but because URIs represent external resources whose validity and permissions cannot be guaranteed after a configuration change.</p><h3>How to preserve an Image</h3><ol><li>Store the selected URI</li></ol><pre>private var selectedImageUri: Uri? = null</pre><p>2. Save it in onSaveInstanceState</p><pre>override fun onSaveInstanceState(outState: Bundle) { <br>super.onSaveInstanceState(outState) <br>outState.putParcelable(&quot;image_uri&quot;, selectedImageUri) <br>}</pre><p>3. Restore it when the view is recreated</p><pre>savedInstanceState?.getParcelable&lt;Uri&gt;(&quot;image_uri&quot;)?.let {<br>selectedImageUri = it <br>imgProfile.setImageURI(it) <br>}</pre><h4>Conclution</h4><p>This behavior might seem confusing at first, but once you understand Android’s view state system, it makes perfect sense:</p><p>Android saves what is safe and lightweight by default and leaves heavy or complex data like images under developer control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a6e86b8a64e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Login to Logout: Simple Session Management in Android using SharedPreferences]]></title>
            <link>https://medium.com/@droiddev5911/from-login-to-logout-simple-session-management-in-android-using-sharedpreferences-db28a18736ad?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/db28a18736ad</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 09:06:23 GMT</pubDate>
            <atom:updated>2026-03-24T14:50:10.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iOt7fvVeWDkNA2F7YIWbg.png" /></figure><p>If you’ve ever opened an app and noticed that it takes you straight to the home screen without asking you to log in again, that’s session management in action.</p><p>In this article, I’ll walk you through a beginner-friendly example of how to build a simple login and logout system in Android using <strong>SharedPreferences</strong> and Kotlin.</p><h3>What is SharedPreferences?</h3><p><strong>SharedPreferences</strong> is a lightweight storage mechanism in Android used to store small amounts of data as <strong>key–value pairs</strong> on the user’s device.</p><p>It is mainly used when you want to <strong>save simple data locally</strong> and retrieve it later, even after the app is closed.</p><h4>Common Use Cases of SharedPref:</h4><ol><li><strong>Login Session Management</strong>: This is the most popular beginner use case.</li></ol><p>2. <strong>Saving User Settings</strong>: Apps often remember user preferences such as:</p><ul><li>Dark mode</li><li>Language</li><li>Notification settings</li></ul><p>3. <strong>App First-Launch Detection.</strong></p><p>4. On Boarding Screen.</p><h3>What We’re Building</h3><p>We’ll create two screens:</p><ul><li><strong>LoginActivity</strong> — where the user enters email and password</li><li><strong>HomeActivity</strong> — where the user lands after successful login</li></ul><p>Once the user logs in, the app will:</p><ul><li>remember the login state</li><li>skip the login screen the next time the app opens</li><li>only return to login after the user presses <strong>Logout in HomeActivity.</strong></li></ul><h3>LoginActivity Setup:</h3><p>In our login screen, we initialize input fields and the login button:</p><pre>lateinit var edtEmailAds: EditText<br>lateinit var edtPassword: EditText<br>lateinit var btnLogin: Button</pre><p>We then connect them to the layout:</p><pre>edtEmailAds = findViewById(R.id.emailEditTxt)<br>edtPassword = findViewById(R.id.passwordEditTxt)<br>btnLogin = findViewById(R.id.loginBtn)</pre><h4>Creating SharedPreferences:</h4><p>This line creates or opens a local storage file:</p><pre>val sharedPreferences = getSharedPreferences(&quot;MyPref&quot;, MODE_PRIVATE)<br>val editor = sharedPreferences.edit()</pre><p><strong>Checking If User Is Already Logged In:</strong></p><p><strong>This is the most important part of session management.</strong></p><pre>val isLoggedIn = sharedPreferences.getBoolean(&quot;isLogin&quot;, false)<br><br>if (isLoggedIn) {<br>    val intent = Intent(this, HomeActivity::class.java)<br>    startActivity(intent)<br>    finish()<br>}</pre><p>When the app opens:</p><ul><li>If isLogin is true user goes directly to HomeActivity</li><li>If false, login screen is shown</li></ul><p>This is how apps “remember” you.</p><h4>Handling Login Button:</h4><p>When the user presses login, we read the input values:</p><pre>val emailAddress = edtEmailAds.text.toString()<br>val password = edtPassword.text.toString()</pre><p>We then check if credentials match:</p><pre>if (emailAddress == &quot;john@gmail.com&quot; &amp;&amp; password == &quot;123456&quot;) {</pre><p>This is just for demo purposes. Real apps would use a server API instead.</p><h4>Saving Login State:</h4><p>Once login is successful, we save the session:</p><pre>editor.putBoolean(&quot;isLogin&quot;, true)<br>editor.apply()</pre><p>This tells the app: <em>User is logged in</em></p><p>After that, we open HomeActivity:</p><pre>startActivity(Intent(this, HomeActivity::class.java))<br>finish()</pre><p>Calling finish() prevents the user from returning to the login screen when pressing the back button.</p><h3>HomeActivity Setup:</h3><p>In HomeActivity, we add a logout button:</p><pre>lateinit var btnLogout: Button<br>btnLogout = findViewById(R.id.logoutBtn)</pre><p>When the logout is pressed:</p><pre>editor.putBoolean(&quot;isLogin&quot;, false)<br>editor.apply()</pre><p>This clears the session and sends the user back to login:</p><pre>startActivity(Intent(this, LoginActivity2::class.java))<br>finish()</pre><h3>Full Code:</h3><h4>LoginActivity2:</h4><pre>package com.example.practiceapps<br><br>import android.content.Intent<br>import android.os.Bundle<br>import android.widget.Button<br>import android.widget.EditText<br>import android.widget.Toast<br>import androidx.activity.enableEdgeToEdge<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.core.view.ViewCompat<br>import androidx.core.view.WindowInsetsCompat<br><br><br>class LoginActivity2 : AppCompatActivity() {<br><br>    lateinit var edtEmailAds: EditText<br>    lateinit var edtPassword: EditText<br>    lateinit var btnLogin: Button<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContentView(R.layout.activity_login2)<br>        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -&gt;<br>            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())<br>            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)<br>            insets<br>        }<br><br>        edtEmailAds = findViewById&lt;EditText&gt;(R.id.emailEditTxt)<br>        edtPassword = findViewById&lt;EditText&gt;(R.id.passwordEditTxt)<br>        btnLogin = findViewById&lt;Button&gt;(R.id.loginBtn)<br><br>        val sharedPreferences = getSharedPreferences(&quot;MyPref&quot;, MODE_PRIVATE)<br>        val editor = sharedPreferences.edit()<br>        val isLoggedIn = sharedPreferences.getBoolean(&quot;isLogin&quot;, false)<br><br>        if (isLoggedIn) {<br>            val intent = Intent(this, HomeActivity::class.java)<br>            startActivity(intent)<br>            finish()<br>        }<br><br>        btnLogin.setOnClickListener {<br><br>            val emailAddress = edtEmailAds.text.toString()<br>            val password = edtPassword.text.toString()<br><br>            if (emailAddress == &quot;john@gmail.com&quot; &amp;&amp; password == &quot;123456&quot;) {<br>                Toast.makeText(this, &quot;Login Successful&quot;, Toast.LENGTH_SHORT).show()<br>                editor.putBoolean(&quot;isLogin&quot;, true)<br>                editor.apply()<br><br>                val intent = Intent(this, HomeActivity::class.java)<br>                startActivity(intent)<br>                finish() // it&#39;s important for proper backstack handling<br>            }<br>            else if (emailAddress.isEmpty()){<br>                Toast.makeText(this, &quot;Enter Mobile No.&quot;, Toast.LENGTH_SHORT).show();<br>            }<br>            else if (password.isEmpty()) {<br>                Toast.makeText(this, &quot;Enter Password&quot;, Toast.LENGTH_SHORT).show();<br>            }<br>            else {<br>                Toast.makeText(this, &quot;Invalid Credentials&quot;, Toast.LENGTH_SHORT).show();<br>            }<br><br>        }<br>    }<br>}</pre><h4>HomeActivity:</h4><pre>package com.example.practiceapps<br><br>import android.content.Intent<br>import android.os.Bundle<br>import android.widget.Button<br>import androidx.activity.enableEdgeToEdge<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.core.view.ViewCompat<br>import androidx.core.view.WindowInsetsCompat<br><br>class HomeActivity : AppCompatActivity() {<br><br>    lateinit var btnLogout: Button<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContentView(R.layout.activity_home)<br><br>        btnLogout = findViewById(R.id.logoutBtn)<br><br>        val sharedPreferences = getSharedPreferences(&quot;MyPref&quot;, MODE_PRIVATE)<br>        val editor = sharedPreferences.edit()<br><br>        btnLogout.setOnClickListener {<br><br>            editor.putBoolean(&quot;isLogin&quot;, false)<br>            editor.apply()<br><br>            val intent = Intent(this, LoginActivity2::class.java)<br>            startActivity(intent)<br>            finish()<br>        }<br><br><br>        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -&gt;<br>            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())<br>            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)<br>            insets<br>        }<br>    }<br>}</pre><p>Screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*xAWPCr6tbGNay56jcTZBGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*2G82LGdj0scYpGuzAfXf_w.png" /></figure><p>In this tutorial, we built a basic login and logout system that demonstrates how an app can remember whether a user is logged in and automatically navigate them to the correct screen. While this approach is perfect for beginners and small applications, it also lays the foundation for understanding more advanced concepts like secure token storage, encrypted preferences, and server-based authentication.</p><p>Thanks for reading this article :) Bye…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db28a18736ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why ConstraintLayout is Better Than LinearLayout and RelativeLayout?]]></title>
            <link>https://medium.com/@droiddev5911/why-constraintlayout-is-better-than-linearlayout-and-relativelayout-bb1beeeae459?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb1beeeae459</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[xml]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 07:56:21 GMT</pubDate>
            <atom:updated>2026-03-17T07:56:21.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1vc1RzY9US4QjhmfdVouw.png" /></figure><p><strong>ConstraintLayout</strong> is a powerful layout system in Android used to design flexible and responsive UI screens.</p><p>Instead of stacking elements one below another (like LinearLayout) or inside each other (like RelativeLayout), <strong>ConstraintLayout lets you position views based on relationships (constraints) with other views or the parent.</strong></p><p>ConstraintLayout = Place UI elements by setting constraints (rules) like “top to top”, “start to end”, etc.</p><h4>Why use ConstraintLayout when we have Relative and Linear Layout in place?</h4><p>ConstraintLayout replaces both LinearLayout and RelativeLayout because it’s more powerful, flexible, and efficient.</p><h4>Problem with LinearLayout:</h4><ul><li>Complex UI needs <strong>multiple nested LinearLayouts</strong></li><li>Deep nesting = <strong>bad performance</strong></li><li>Hard to align elements precisely</li></ul><h4>Problem with RelativeLayout:</h4><ul><li>Becomes <strong>confusing in a complex UI</strong></li><li>Still may need nesting</li><li>Performance is not great compared to the modern approach</li></ul><h3>Example of RelativeLayout:</h3><pre>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;!-- TextView at the top center --&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_centerHorizontal=&quot;true&quot;<br>        android:layout_marginTop=&quot;20dp&quot;<br>        android:text=&quot;Hello Android&quot;<br>        android:textSize=&quot;20sp&quot; /&gt;<br><br>    &lt;!-- Button below TextView --&gt;<br>    &lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_below=&quot;@id/title&quot;<br>        android:layout_centerHorizontal=&quot;true&quot;<br>        android:layout_marginTop=&quot;20dp&quot;<br>        android:text=&quot;Click Me&quot; /&gt;<br>    <br>    &lt;!--    place a button at the center of the screen--&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button2&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_centerInParent=&quot;true&quot;<br>        android:text=&quot;Login In&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/title2&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:textAlignment=&quot;center&quot;<br>        android:layout_below=&quot;@+id/button2&quot;<br>        android:text=&quot;RelativeLayout is an Android layout that lets you position UI elements relative to each other or to the parent container. Instead of arranging views in a straight line, you can place them using rules like below another view, to the right of, or center in parent.&quot;<br>        android:textSize=&quot;20sp&quot; /&gt;<br><br>    &lt;!-- Image aligned at bottom right --&gt;<br>    &lt;ImageView<br>        android:layout_width=&quot;50dp&quot;<br>        android:layout_height=&quot;50dp&quot;<br>        android:layout_alignParentEnd=&quot;true&quot;<br>        android:layout_alignParentBottom=&quot;true&quot;<br>        android:layout_margin=&quot;16dp&quot;<br>        android:src=&quot;@android:drawable/ic_menu_camera&quot; /&gt;<br><br>&lt;/RelativeLayout&gt;</pre><p>RelativeLayout works using rules like: <strong>Place this view relative to parent or another view.</strong></p><h4>Screenshot:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*w-5MrPwKS3H5tM2VCOBVwA.png" /><figcaption>(Using RelativeLayout)</figcaption></figure><p><strong>Main attributes of RelativeLayout</strong> you should know</p><h4>Position Relative to Parent:</h4><ul><li>android:layout_alignParentTop=&quot;true&quot; → Align to top</li><li>android:layout_alignParentBottom=&quot;true&quot; → Align to bottom</li><li>android:layout_alignParentStart=&quot;true&quot; → Align to left</li><li>android:layout_alignParentEnd=&quot;true&quot; → Align to right</li><li>android:layout_centerInParent=&quot;true&quot; → Center (both directions)</li><li>android:layout_centerHorizontal=&quot;true&quot; → Center horizontally</li><li>android:layout_centerVertical=&quot;true&quot; → Center vertically</li></ul><h4>Position Relative to Another View:</h4><ul><li>android:layout_below=&quot;@id/viewId&quot; → Place below a view</li><li>android:layout_above=&quot;@id/viewId&quot; → Place above a view</li><li>android:layout_toStartOf=&quot;@id/viewId&quot; → Left of a view</li><li>android:layout_toEndOf=&quot;@id/viewId&quot; → Right of a view</li><li>android:layout_alignTop=&quot;@id/viewId&quot; → Align top edges</li><li>android:layout_alignBottom=&quot;@id/viewId&quot; → Align bottom edges</li><li>android:layout_alignStart=&quot;@id/viewId&quot; → Align left edges</li><li>android:layout_alignEnd=&quot;@id/viewId&quot; → Align right edges</li></ul><h3>Example of LinearLayout:</h3><pre>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;!-- Top Section --&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Hello Android&quot;<br>        android:textSize=&quot;20sp&quot;<br>        android:layout_gravity=&quot;center_horizontal&quot;<br>        android:layout_marginTop=&quot;20dp&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Click Me&quot;<br>        android:layout_gravity=&quot;center_horizontal&quot;<br>        android:layout_marginTop=&quot;20dp&quot; /&gt;<br><br>    &lt;!-- Center Section --&gt;<br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:layout_weight=&quot;1&quot;<br>        android:gravity=&quot;center&quot;<br>        android:orientation=&quot;vertical&quot;&gt;<br><br>        &lt;!-- Center Button --&gt;<br>        &lt;Button<br>            android:id=&quot;@+id/button2&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;Login In&quot; /&gt;<br><br>        &lt;!-- Text BELOW Login Button --&gt;<br>        &lt;TextView<br>            android:id=&quot;@+id/title2&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:textAlignment=&quot;center&quot;<br>            android:text=&quot;RelativeLayout is an Android layout that lets you position UI elements relative to each other or to the parent container. Instead of arranging views in a straight line, you can place them using rules like below another view, to the right of, or center in parent.&quot;<br>            android:textSize=&quot;20sp&quot;<br>            android:layout_marginTop=&quot;10dp&quot;/&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;!-- Bottom Right Image --&gt;<br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:gravity=&quot;end&quot;&gt;<br><br>        &lt;ImageView<br>            android:layout_width=&quot;50dp&quot;<br>            android:layout_height=&quot;50dp&quot;<br>            android:layout_margin=&quot;16dp&quot;<br>            android:src=&quot;@android:drawable/ic_menu_camera&quot; /&gt;<br>    &lt;/LinearLayout&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>Screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*w-5MrPwKS3H5tM2VCOBVwA.png" /></figure><h4><strong>Common attributes of LinearLayout</strong> you should know:</h4><ul><li>android:orientation=&quot;vertical&quot; → Arrange views top to bottom</li><li>android:orientation=&quot;horizontal&quot; → Arrange views left to right</li><li>android:gravity=&quot;center&quot; → Center all child views</li><li>android:gravity=&quot;center_horizontal&quot; → Center horizontally</li><li>android:gravity=&quot;center_vertical&quot; → Center vertically</li><li>android:gravity=&quot;end&quot; → Align to right</li><li>android:gravity=&quot;start&quot; → Align to left</li><li>android:layout_gravity=&quot;center&quot; → Center a single view</li><li>android:layout_gravity=&quot;end&quot; → Move view to right</li><li>android:layout_gravity=&quot;start&quot; → Move view to left</li><li>android:layout_weight=&quot;1&quot; → Take equal space</li><li>android:layout_weight=&quot;2&quot; → Take more space proportionally</li><li>android:layout_height=&quot;0dp&quot; (vertical layout)</li><li>android:layout_width=&quot;0dp&quot; (horizontal layout)</li></ul><h4>Which is more efficient: LinearLayout or RelativeLayout?</h4><p><strong>LinearLayout is generally more efficient</strong> because it has a simpler layout structure and requires less computation.</p><h4>Why is LinearLayout faster?</h4><p>LinearLayout arranges views in a single direction (vertical or horizontal), so it performs fewer calculations while measuring and drawing the UI.</p><h4>Does that mean LinearLayout is always better?</h4><p>No. If you use <strong>too many nested LinearLayouts</strong>, performance can drop significantly.</p><h4>What is the best layout for performance in modern Android?</h4><p><strong>ConstraintLayout</strong> is the best choice because it avoids nesting and provides better performance and flexibility.</p><h3>Why ConstraintLayout is Better</h3><p>ConstraintLayout is better than LinearLayout and RelativeLayout because it allows you to design complex and responsive user interfaces using a single, flat layout structure, which significantly improves app performance by reducing view hierarchy depth. Unlike LinearLayout, which often requires multiple nested layouts, and RelativeLayout, which can become confusing in complex designs, ConstraintLayout gives you precise control over positioning through flexible constraints. This makes it easier to align, center, and arrange views relative to each other or the parent without unnecessary nesting. Additionally, it adapts well to different screen sizes and resolutions, making your UI more scalable and modern. Overall, ConstraintLayout combines performance, flexibility, and simplicity, making it the preferred choice for modern Android development.</p><h4>Example of Constraint Layout:</h4><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:id=&quot;@+id/main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;!-- Top Title --&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Hello Android&quot;<br>        android:textSize=&quot;20sp&quot;<br>        android:layout_marginTop=&quot;20dp&quot;<br><br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>    &lt;!-- Button below Title --&gt;<br>    &lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Click Me&quot;<br>        android:layout_marginTop=&quot;20dp&quot;<br><br>        app:layout_constraintTop_toBottomOf=&quot;@id/title&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>    &lt;!-- Center Button --&gt;<br>    &lt;Button<br>        android:id=&quot;@+id/button2&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Login In&quot;<br><br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>    &lt;!-- Text below Login Button --&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/title2&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:textAlignment=&quot;center&quot;<br>        android:text=&quot;RelativeLayout is an Android layout that lets you position UI elements relative to each other or to the parent container. Instead of arranging views in a straight line, you can place them using rules like below another view, to the right of, or center in parent.&quot;<br>        android:textSize=&quot;20sp&quot;<br>        android:layout_marginTop=&quot;10dp&quot;<br><br>        app:layout_constraintTop_toBottomOf=&quot;@id/button2&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>    &lt;!-- Bottom Right Image --&gt;<br>    &lt;ImageView<br>        android:layout_width=&quot;50dp&quot;<br>        android:layout_height=&quot;50dp&quot;<br>        android:layout_margin=&quot;16dp&quot;<br>        android:src=&quot;@android:drawable/ic_menu_camera&quot;<br><br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>Screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*V6cUR-0l11HVpOCsUSB7ig.png" /></figure><h4>Common attributes of ConstraintLayout you should know:</h4><p>Position Relative to Parent:</p><ul><li>app:layout_constraintTop_toTopOf=&quot;parent&quot; → Align to top</li><li>app:layout_constraintBottom_toBottomOf=&quot;parent&quot; → Align to bottom</li><li>app:layout_constraintStart_toStartOf=&quot;parent&quot; → Align to left</li><li>app:layout_constraintEnd_toEndOf=&quot;parent&quot; → Align to right</li></ul><p>Position Relative to Another View:</p><ul><li>app:layout_constraintTop_toBottomOf=&quot;@id/viewId&quot; → Place below a view</li><li>app:layout_constraintBottom_toTopOf=&quot;@id/viewId&quot; → Place above a view</li><li>app:layout_constraintStart_toEndOf=&quot;@id/viewId&quot; → Place right of a view</li><li>app:layout_constraintEnd_toStartOf=&quot;@id/viewId&quot; → Place left of a view</li></ul><p>Bias (Fine Control):</p><ul><li>app:layout_constraintHorizontal_bias=&quot;0.3&quot; → Move left/right</li><li>app:layout_constraintVertical_bias=&quot;0.7&quot; → Move up/down</li></ul><p>Range: 0.0 → 1.0</p><p>Chains (Align Multiple Views):</p><ul><li>Automatically align multiple views in a row/column</li></ul><p>Types:</p><ul><li>spread</li><li>spread_inside</li><li>packed</li></ul><h3>🚀 Why ConstraintLayout is Better</h3><ul><li>✅ <strong>Flat layout structure</strong> → No deep nesting</li><li>✅ <strong>Better performance</strong> → Faster UI rendering</li><li>✅ <strong>Handles complex UI easily</strong> → No need for multiple layouts</li><li>✅ <strong>Flexible positioning</strong> → Place views anywhere using constraints</li><li>✅ <strong>Responsive design</strong> → Works well on all screen sizes</li><li>✅ <strong>Reduces code complexity</strong> → Cleaner XML</li><li>✅ <strong>Supports chains &amp; bias</strong> → Fine control over alignment</li><li>✅ <strong>Powerful UI tools</strong> → Great support in Android Studio</li><li>✅ <strong>Replaces Linear &amp; RelativeLayout</strong> → One layout for all needs</li><li>✅ <strong>Modern standard</strong> → Recommended by Google</li></ul><p>ConstraintLayout makes Android UI design simpler, cleaner, and more efficient. Once you start using it, you’ll realize how powerful and flexible it is compared to older layouts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1beeeae459" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Complexity and Space Complexity Explained with Android Specific Examples]]></title>
            <link>https://medium.com/@droiddev5911/time-complexity-and-space-complexity-explained-with-android-specific-examples-36c3e01e4e10?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c3e01e4e10</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 17:06:00 GMT</pubDate>
            <atom:updated>2026-02-21T17:06:00.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrQtvnE__peRfK65MT_rWQ.png" /></figure><p>As Android developers, we often focus on UI, architecture, and user experience. But under the hood, performance matters just as much.</p><p>Why does a RecyclerView lag with large data?<br> Why does an app freeze when processing a big list?<br> Why does memory usage spike after loading images?</p><p>The answer often lies in <strong>Time Complexity</strong> and <strong>Space Complexity</strong>.</p><p>In this article, we’ll break down both concepts with practical Android-specific examples.</p><h3>What is Time Complexity?</h3><p>Time Complexity measures <strong>how long an algorithm takes to run</strong> as the input size increases. It doesn’t measure exact seconds. It measures <strong>growth rate</strong>.</p><p>For example:</p><ul><li>Processing 10 items → fast</li><li>Processing 10,000 items → suddenly slow</li></ul><p>That growth pattern is time complexity.</p><h3>What is Space Complexity?</h3><p>Space Complexity measures <strong>how much memory an algorithm uses</strong> as the input size increases.</p><p>In Android, memory matters a lot because:</p><ul><li>Devices have limited RAM</li><li>Memory leaks cause crashes</li><li>High memory usage leads to OOM (OutOfMemoryError)</li></ul><p>Space complexity helps you understand how memory scales.</p><h3>Understanding Big-O Notation</h3><p><strong>Big-O Notation</strong> is a mathematical way to describe how fast an algorithm grows as the input size (<strong>n</strong>) increases. Basically, it tells: “If my input size increases, how much slower (or bigger in memory) will my program become?”</p><pre>Complexity               Meaning               Android Example<br> <br>O(1)                     Constant             Accessing a Map value<br><br>O(n)                      Linear              Looping through a list<br><br>O(log n).                 Logarithmic           Binary search<br><br>O(n log n)                Sorting               Sorting messages<br><br>O(n²)                    Quadratic.               Nested loops</pre><p>Big-O is about <strong>growth rate</strong>, not exact speed.</p><p>If n becomes very large:</p><ul><li>O(1) → Still fast</li><li>O(n) → Slower</li><li>O(n²) → Very slow</li><li>O(log n) → Very efficient</li></ul><p>Big-O helps you answer this critical question:</p><p><em>“Will my app still perform well when I have 10 users… or 10 million users?”</em></p><p>If you’re building Android apps that handle lists, APIs, databases, or background processing, understanding these ideas is not optional. It’s essential.</p><h3>What Is Time Complexity?</h3><p>Time Complexity describes how the execution time of an algorithm grows as the input size increases.</p><p>We express it using <strong>Big-O notation</strong>, which focuses on worst-case growth.</p><p>For example:</p><ul><li><strong>O(1)</strong> — Constant time</li><li><strong>O(n)</strong> — Linear time</li><li><strong>O(log n)</strong> — Logarithmic time</li><li><strong>O(n²)</strong> — Quadratic time</li></ul><p>The important idea is growth rate. If your input doubles, how much more work does your algorithm do?</p><p>Let’s look at an Android-specific example.</p><p>Imagine you have a list of 10,000 users fetched from an API.</p><p>If you loop through all users:</p><pre>for (user in userList) {<br>    println(user.name)<br>}</pre><p>This is <strong>O(n)</strong>. If users increase from 10,000 to 20,000, the work doubles.</p><p>Now imagine nested loops:</p><pre>for (user in userList) {<br>    for (friend in userList) {<br>        println(user.name + friend.name)<br>    }<br>}</pre><p>This becomes <strong>O(n²)</strong>. If the list doubles, the work becomes four times larger. That’s dangerous in mobile apps where performance and battery matter.</p><p>Time complexity helps you predict lag before users experience it.</p><h3>What Is Space Complexity?</h3><p>Space Complexity measures how much extra memory an algorithm uses as input size grows.</p><p>On Android, memory matters even more than time. Devices have limited RAM. Poor memory decisions can lead to garbage collection pressure, frame drops, or even crashes.</p><p>Consider this example:</p><pre>fun duplicateList(list: List&lt;Int&gt;): List&lt;Int&gt; {<br>    val newList = mutableListOf&lt;Int&gt;()<br>    for (item in list) {<br>        newList.add(item)<br>    }<br>    return newList<br>}</pre><p>Here, we create a new list of the same size. That means space grows proportionally with input size: <strong>O(n)</strong> space complexity.</p><p>Now compare it with:</p><pre>fun printList(list: List&lt;Int&gt;) {<br>    for (item in list) {<br>        println(item)<br>    }<br>}</pre><p>This uses only a few variables regardless of list size. That’s <strong>O(1)</strong> space complexity.</p><p>In Android, inefficient space usage can:</p><ul><li>Increase garbage collection frequency</li><li>Slow down UI rendering</li><li>Cause OutOfMemoryError</li></ul><p>So space complexity is not theoretical, it directly affects user experience.</p><h3>Time vs Space: The Trade-off</h3><p>Sometimes we intentionally use more memory to improve speed.</p><p>For example, using a HashMap for quick lookups:</p><pre>val userMap = mutableMapOf&lt;String, User&gt;()</pre><p>Lookup by key is fast (average O(1)), but the map consumes more memory than a simple list.</p><p>This is a common engineering trade-off:</p><ul><li>More memory → faster execution</li><li>Less memory → potentially slower operations</li></ul><p>Good developers don’t chase one metric blindly. They balance both.</p><h3>Android-Specific Performance Thinking</h3><p>Consider a RecyclerView showing 5,000 items.</p><p>If every time the user scrolls you:</p><ul><li>Recalculate heavy logic inside onBindViewHolder</li><li>Sort the list repeatedly</li><li>Perform nested filtering</li></ul><p>You may accidentally introduce O(n²) behavior inside UI rendering.</p><p>Instead, you should:</p><ul><li>Precompute expensive operations</li><li>Use DiffUtil efficiently</li><li>Cache results when possible</li></ul><p>Understanding complexity helps you see performance problems before profiling tools do.</p><h3>Why Big-O Focuses on Growth</h3><p>Big-O does not care about small input sizes.</p><p>An O(n²) algorithm may feel fast for 10 items.<br>It becomes disastrous for 10,000 items.</p><p>Mobile apps often start small in development but grow large in production with real user data. Complexity thinking protects your app from scaling failures.</p><h3>A Practical Mental Model</h3><p>Whenever you write code, ask:</p><ul><li>Does this loop depend on input size?</li><li>Am I nesting loops?</li><li>Am I creating extra collections unnecessarily?</li><li>Will this run on the main thread?</li></ul><p>If the answer suggests growth proportional to input, think about optimization early.</p><h3>Final Thoughts</h3><p>Time Complexity tells you how fast your algorithm grows.<br>Space Complexity tells you how much memory it consumes as it grows.</p><p>Together, they form the foundation of scalable Android engineering.</p><p>Writing efficient code is not about premature optimization.<br>It’s about writing code that still works smoothly when your app has 10 users and when it has 10 million.</p><p>And that’s the difference between code that runs… and code that scales.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c3e01e4e10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Server Driven UI(SDUI) in Android Development?]]></title>
            <link>https://medium.com/@droiddev5911/server-driven-ui-sdui-in-android-modern-app-architecture-939e385bc722?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/939e385bc722</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 15:11:43 GMT</pubDate>
            <atom:updated>2026-02-21T15:15:14.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6-1RdfxBOzY6uB6kgGJtg.png" /></figure><p>Modern Android development is no longer just about writing XML or composables. It’s about building scalable systems that allow products to evolve quickly.</p><p>One powerful architectural pattern that enables this flexibility is <strong>Server Driven UI (SDUI)</strong>.</p><p>In this article, we’ll break down what it is, why it matters, how it works, and when you should (or shouldn’t) use it.</p><h4>What is Server Driven UI?</h4><p>Server Driven UI is an architectural approach where the <strong>backend controls the structure and configuration of the UI</strong>, and the Android client dynamically renders components based on server responses.</p><p>Instead of hardcoding layouts inside the app, the server sends structured data (usually JSON) describing:</p><ul><li>What components to show</li><li>In what order</li><li>With what data</li><li>Sometimes even styling and behavior</li></ul><p>The app acts as a renderer.</p><h4>Why Traditional UI Approaches Fall Short</h4><p>In traditional Android development:</p><ul><li>UI is defined in XML or Compose.</li><li>Any structural change requires a new app release.</li><li>Users must update the app to see changes.</li></ul><p>This slows down:</p><ul><li>A/B testing</li><li>Feature experimentation</li><li>UI iteration</li><li>Emergency fixes</li></ul><p>In fast-moving product environments, this becomes a bottleneck.</p><h4>How Server Driven UI Works</h4><p>Here’s the simplified flow:</p><ol><li>App requests screen configuration from API</li><li>Server returns structured JSON</li><li>App parses JSON into UI models</li><li>App dynamically renders the component.</li></ol><p>The backend becomes the decision-maker. The app becomes the interpreter.</p><h4>Real-World Example: E-commerce Home Screen</h4><p>Imagine building a home screen like: Amazon &amp; Flipkart</p><p>Instead of hardcoding:</p><ul><li>Promotional banner</li><li>“Recommended for You” title</li><li>Product list</li><li>CTA button</li></ul><h4>The server returns:</h4><pre>{<br>  &quot;components&quot;: [<br>    { &quot;type&quot;: &quot;banner&quot;, &quot;imageUrl&quot;: &quot;sale.jpg&quot; },<br>    { &quot;type&quot;: &quot;title&quot;, &quot;text&quot;: &quot;Recommended for You&quot; },<br>    { &quot;type&quot;: &quot;product_list&quot; },<br>    { &quot;type&quot;: &quot;button&quot;, &quot;text&quot;: &quot;View All&quot; }<br>  ]<br>}</pre><p>Now the backend can:</p><ul><li>Reorder sections</li><li>Remove components</li><li>Add new features</li><li>Show different layouts to different users</li></ul><p>All without a Play Store update.</p><h4>Implementing SDUI in Android</h4><p>Step 1: Define UI Models</p><pre>sealed class UiComponent {<br>    data class Banner(val imageUrl: String) : UiComponent()<br>    data class Title(val text: String) : UiComponent()<br>    data class Button(val text: String) : UiComponent()<br>}</pre><p>Step 2: Render Dynamically (Compose Example)</p><pre>@Composable<br>fun RenderComponent(component: UiComponent) {<br>    when (component) {<br>        is UiComponent.Banner -&gt; AsyncImage(model = component.imageUrl, contentDescription = null)<br>        is UiComponent.Title -&gt; Text(component.text)<br>        is UiComponent.Button -&gt; Button(onClick = { }) {<br>            Text(component.text)<br>        }<br>    }<br>}</pre><p>This pattern allows the UI to adapt to server responses dynamically.</p><h4>Let’s see how we can achieve this in XML:</h4><p>Since XML is not declarative like Compose, we can’t directly write a when like that inside XML. Instead, we:</p><ol><li>Define separate XML layouts for each component</li><li>Inflate them dynamically</li><li>Bind data in Kotlin</li></ol><p>Let’s convert your Compose example into a proper XML-based SDUI setup.</p><p>Step 1: Create Separate XML Layouts</p><pre><br>banner_layout.xml<br><br>&lt;ImageView<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/bannerImage&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;200dp&quot;<br>    android:scaleType=&quot;centerCrop&quot; /&gt;<br><br>title_layout.xml<br><br>&lt;TextView<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/titleText&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:textSize=&quot;20sp&quot;<br>    android:padding=&quot;16dp&quot;<br>    android:textStyle=&quot;bold&quot; /&gt;<br><br>button_layout.xml<br><br>&lt;Button<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/actionButton&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_margin=&quot;16dp&quot; /&gt;<br><br>activity_main.xml<br>Parent Container Layout<br><br>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:id=&quot;@+id/container&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot; /&gt;</pre><h4>Render Dynamically in Kotlin</h4><pre>fun renderComponent(component: UiComponent, context: Context, container: LinearLayout) {<br><br>    when (component) {<br><br>        is UiComponent.Banner -&gt; {<br>            val view = LayoutInflater.from(context)<br>                .inflate(R.layout.banner_layout, container, false)<br><br>            val imageView = view.findViewById&lt;ImageView&gt;(R.id.bannerImage)<br>            Glide.with(context).load(component.imageUrl).into(imageView)<br><br>            container.addView(view)<br>        }<br><br>        is UiComponent.Title -&gt; {<br>            val view = LayoutInflater.from(context)<br>                .inflate(R.layout.title_layout, container, false)<br><br>            val textView = view.findViewById&lt;TextView&gt;(R.id.titleText)<br>            textView.text = component.text<br><br>            container.addView(view)<br>        }<br><br>        is UiComponent.Button -&gt; {<br>            val view = LayoutInflater.from(context)<br>                .inflate(R.layout.button_layout, container, false)<br><br>            val button = view.findViewById&lt;Button&gt;(R.id.actionButton)<br>            button.text = component.text<br><br>            container.addView(view)<br>        }<br>    }<br>}</pre><h4>Render Dynamically in Kotlin</h4><pre>fun renderComponent(component: UiComponent, context: Context, container: LinearLayout) {<br><br>    when (component) {<br><br>        is UiComponent.Banner -&gt; {<br>            val view = LayoutInflater.from(context)<br>                .inflate(R.layout.banner_layout, container, false)<br><br>            val imageView = view.findViewById&lt;ImageView&gt;(R.id.bannerImage)<br>            Glide.with(context).load(component.imageUrl).into(imageView)<br><br>            container.addView(view)<br>        }<br><br>        is UiComponent.Title -&gt; {<br>            val view = LayoutInflater.from(context)<br>                .inflate(R.layout.title_layout, container, false)<br><br>            val textView = view.findViewById&lt;TextView&gt;(R.id.titleText)<br>            textView.text = component.text<br><br>            container.addView(view)<br>        }<br><br>        is UiComponent.Button -&gt; {<br>            val view = LayoutInflater.from(context)<br>                .inflate(R.layout.button_layout, container, false)<br><br>            val button = view.findViewById&lt;Button&gt;(R.id.actionButton)<br>            button.text = component.text<br><br>            container.addView(view)<br>        }<br>    }<br>}</pre><h3>Key Difference from Compose</h3><h3>Compose:</h3><ul><li>Declarative</li><li>UI auto-updates with state</li><li>Cleaner dynamic rendering</li></ul><h3>XML View System:</h3><ul><li>Imperative</li><li>Requires inflation</li><li>More boilerplate</li><li>Manual view handling</li></ul><h3>Disadvantages of Server Driven UI in Android</h3><p>Checkout this interesting discussion of SDUI on <a href="https://www.reddit.com/r/androiddev/comments/1ejngo9/server_driven_ui_is_this_really_worth_it/">Reddit</a>.</p><p>SDUI introduces:</p><ul><li>JSON parsing layers</li><li>UI mapping logic</li><li>Schema handling</li><li>Version compatibility</li></ul><p>Your UI is no longer “just UI”, it becomes a rendering engine. This adds architectural complexity.</p><h4>Tight Backend Dependency</h4><p>Your app becomes highly dependent on backend:</p><ul><li>If API fails → UI may break</li><li>If schema changes → app may crash</li><li>If response is slow → screen loading is delayed</li></ul><p>You must always build:</p><ul><li>Safe defaults</li><li>Fallback UI</li><li>Strong validation</li></ul><h4>Harder Debugging</h4><p>Traditional UI bug: <em>“Button not aligned properly.”</em></p><p>SDUI bug: <em>“Is it server issue? Mapping issue? Version mismatch? Parsing issue?”</em></p><p>Debugging becomes a mess.</p><h4>Versioning Problems</h4><p>You must handle: Backward compatibility, Schema versioning, Deprecation strategy. Without proper planning, SDUI can break older clients.</p><h4>Limited Native Control</h4><p>SDUI works great for: Layout flexibility, Content-driven screens</p><p>But it struggles with: Complex animations, Deep gesture handling, Heavy hardware integrations, and Advanced navigation logic. Not every UI should be server-driven.</p><h3>When SDUI Becomes a Bad Idea</h3><p>Avoid SDUI if:</p><ul><li>Your app is small</li><li>UI rarely changes</li><li>Team size is limited</li><li>Backend team is weak</li><li>You don’t need experimentation</li></ul><p>Most of the time simple XML/Compose is better.</p><h3>Real-World Use Cases of Server Driven UI</h3><h4>Promotional Offers &amp; Flash Sales</h4><ul><li>Diwali sale</li><li>Black Friday</li><li>Flash deals</li></ul><p>The backend dynamically controls:</p><ul><li>Banner images</li><li>Discount percentage</li><li>Countdown timers</li><li>CTA buttons</li></ul><h4>Dynamic Home Screen Personalization</h4><p>Apps show different layouts based on:</p><ul><li>User behavior</li><li>Location</li><li>Purchase history</li><li>Subscription level</li></ul><p>For example:</p><ul><li>Premium user sees “Exclusive Deals”</li><li>New user sees “Welcome Bonus”</li><li>Returning user sees “Recommended For You”</li></ul><p>This layout variation is often server-driven.</p><h3>Conclusion</h3><p>Server Driven UI is not just a technical pattern, it’s a strategic architectural decision. It shifts control from app releases to backend configuration, enabling faster experimentation, dynamic personalization, and greater product agility.</p><p>The article below explains implementing server-driven UI in detail, check it out:</p><p><a href="https://proandroiddev.com/dynamic-screens-using-server-driven-ui-in-android-262f1e7875c1">Dynamic screens using server-driven UI in Android</a></p><p>However, with that flexibility comes complexity. SDUI demands careful schema design, version management, strong fallback strategies, and close collaboration between mobile and backend teams. Without proper planning, it can quickly become difficult to debug and maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939e385bc722" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Messy UI Logic to Clean Architecture: Understanding ViewModel in Android]]></title>
            <link>https://medium.com/@droiddev5911/from-messy-ui-logic-to-clean-architecture-understanding-viewmodel-in-android-8f6cbe74bcf9?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6cbe74bcf9</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 11:40:16 GMT</pubDate>
            <atom:updated>2026-02-20T11:40:16.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0yu_J12yT-i6GZGUYMD8A.png" /></figure><p>ViewModel is not just another architecture component. It is the backbone of scalable Android applications.</p><p>When <strong>UI logic</strong> and <strong>business logic</strong> live together, applications become harder to test, harder to maintain, and more fragile during configuration changes. By introducing ViewModel, we enforce separation of concerns, improve testability, and create a clean state management system that survives lifecycle changes.</p><p>In Jetpack Compose, this becomes even more important. Since composables can recompose frequently, keeping logic inside them leads to unpredictable behavior. ViewModel acts as a stable state holder that drives the UI in a predictable and maintainable way.</p><p>If you’re building anything beyond a demo app, ViewModel is not optional, it is essential.</p><p>First, let’s go through the difference between business logic and UI logic.</p><h3>Business Logic:</h3><p>Business logic is the set of rules and decisions that define how your application behaves. It represents the <strong>“brain”</strong> of your app. Business logic is code that enforces rules, processes data, and decides how the app should behave.</p><h4>Real-World Example (Food Delivery App)</h4><p>Business logic:</p><ul><li>If order &gt; 500 → free delivery</li><li>If restaurant closed → block order</li><li>If payment fails → retry 3 times</li><li>If password wrong → show error</li></ul><p>These are rules that define how the system behaves.</p><p>Code Example:</p><pre>if (count &gt;= 10) {<br>    showAchievement()<br>}<br><br>fun calculateDiscount(price: Double): Double {<br>    return price * 0.9<br>}<br><br>fun validateLogin(email: String, password: String): Boolean {<br>    return email.contains(&quot;@&quot;) &amp;&amp; password.length &gt; 6<br>}</pre><p>These are rules and decisions i.e. business logic.</p><h3>What Is UI Logic?</h3><p>UI logic is the code that controls how the user interface looks and behaves visually. It does NOT decide business rules. It only decides <strong>how things are shown on screen.</strong></p><p>Example:</p><ol><li>Showing or hiding something: This only affects visibility.</li></ol><pre>if (count &gt; 0) {<br>    Text(&quot;You&#39;ve had $count glasses.&quot;)<br>}</pre><p>2. Enabling or disabling a button: This controls UI state, not app rules.</p><pre>Button(<br>    enabled = count &lt; 10,<br>    onClick = { onIncrement() }<br>)</pre><p>3. Showing loading indicator</p><pre>if (isLoading) {<br>    CircularProgressIndicator()<br>}</pre><h3>Let’s learn about ViewModel</h3><p><a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModels</a> provide the UI state and access to the business logic located in other layers of the app. Additionally, ViewModels survive configuration changes, so they have a longer lifetime than the Composition. They can follow the lifecycle of the host of Compose content, that is: activities, fragments, or the destination of a Navigation graph if you’re using Compose Navigation.</p><h4>Why we don’t use &#39;remember&#39; inside ViewModel:</h4><p>We don’t use remember inside a ViewModel because remember belongs to the Compose UI lifecycle, while ViewModel belongs to the Android lifecycle.</p><p><strong>In Jetpack Compose, we use remember:</strong></p><pre>var count by remember { mutableStateOf(0) }</pre><ul><li>Stores state <strong>inside the composition</strong></li><li>Survives recomposition</li><li>Dies when composable leaves the screen</li></ul><p>It is <strong>UI-scoped state</strong>.</p><p><strong>In Android Jetpack, we use:</strong></p><pre>class CounterViewModel : ViewModel() {<br>    var count by mutableStateOf(0)<br>}</pre><p>ViewModel:</p><ul><li>Survives configuration changes</li><li>Lives outside composables</li><li>Is lifecycle-aware (Activity/Fragment scope)</li><li>Does NOT depend on Compose</li></ul><p>It is <strong>screen-scoped state</strong>.</p><p>remember only works inside a composition.</p><pre>@Composable<br>fun Something() { }</pre><p>A ViewModel is NOT a composable. So technically, you can’t even use it there.</p><blockquote>There is a very deep concept of how viewmodel works internally. I will go throught it in some other article.</blockquote><h4>Enough Theory so far. Let’s look at a simple app:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*NaHlq2pMUpc_hfmBlqpcaQ.png" /></figure><h4>Here is the code inside MainActivity without using a ViewModel:</h4><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            BasicStateCodelabTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    WellnessScreen()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun WellnessScreen(modifier: Modifier = Modifier) {<br><br>    Column(modifier = modifier) {<br>        StatefulCounter()<br><br>        val list = remember { getWellnessTasks().toMutableStateList() }<br><br>        WellnessTasksList(<br>            list = list,<br>            onCloseTask = { task -&gt; list.remove(task) })<br>    }<br>}<br><br>@Composable<br>fun StatefulCounter(modifier: Modifier = Modifier) {<br>    var count by rememberSaveable { mutableStateOf(0) }<br>    StatelessCounter(count, { count++ }, modifier)<br>}<br><br>@Composable<br>fun StatelessCounter(count: Int, onIncrement: () -&gt; Unit, modifier: Modifier = Modifier) {<br>    Column(modifier = modifier.padding(16.dp)) {<br>        if (count &gt; 0) {<br>            Text(&quot;You&#39;ve had $count glasses.&quot;)<br>        }<br>        Button(onClick = onIncrement, Modifier.padding(top = 8.dp), enabled = count &lt; 10) {<br>            Text(&quot;Add one&quot;)<br>        }<br>    }<br>}<br><br>@Composable<br>fun WellnessTasksList(<br>    list: List&lt;WellnessTask&gt;,<br>    onCloseTask: (WellnessTask) -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br><br>    LazyColumn(<br>        modifier = modifier<br>    ) {<br>        items(<br>            items = list,<br>            key = { task -&gt; task.id }<br>        ) { task -&gt;<br>            WellnessTaskItem(<br>                taskName = task.label,<br>                onClose = { onCloseTask(task) }<br>            )<br>        }<br>    }<br>}<br><br>@Composable<br>fun WellnessTaskItem(<br>    taskName: String,<br>    onClose: () -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br><br>    var checked by rememberSaveable { mutableStateOf(false) }<br><br>    Row(<br>        modifier = modifier, verticalAlignment = Alignment.CenterVertically<br>    ) {<br>        Text(<br>            modifier = Modifier<br>                .weight(1f)<br>                .padding(start = 16.dp),<br>            text = taskName<br>        )<br>        Checkbox(<br>            checked = checked,<br>            onCheckedChange = { checked = it },<br>        )<br>        IconButton(onClick = onClose) {<br>            Icon(Icons.Filled.Close, contentDescription = &quot;Close&quot;)<br>        }<br>    }<br>}</pre><p>In the code above, <strong>we have mixed business logic and UI logic together.</strong></p><h4>Let’s list down what are the business logic is in this App:</h4><ol><li>Counter Increment Rule</li></ol><pre>    var count by rememberSaveable { mutableStateOf(0) }<br>    StatelessCounter(count, { count++ }, modifier)</pre><p>That is business logic because:</p><ul><li>It changes application state</li><li>It controls behavior</li><li>It represents a rule (increment count)</li></ul><p>2. Removing a Task</p><pre>val list = remember { getWellnessTasks().toMutableStateList() }<br><br> WellnessTasksList(<br>            list = list,<br>            onCloseTask = { task -&gt; list.remove(task) })</pre><p>This is business logic because:</p><ul><li>It mutates the data source</li><li>It controls what data exists</li><li>It changes the app state</li></ul><p>This is NOT just UI rendering: this affects the actual data model.</p><p>3. Task List Creation</p><pre>val list = remember { getWellnessTasks().toMutableStateList() }</pre><p>Creating and owning the list of tasks is also business/data logic.</p><p><strong>You might be saying that the line below also comes under business logic but they are UI logic and they only control visual behavior.</strong></p><pre>if (count &gt; 0) {<br> Text(&quot;You&#39;ve had $count glasses.&quot;)<br>}<br><br>Button(enabled = count &lt; 10)<br><br>Checkbox(<br>    checked = checked,<br>    onCheckedChange = { checked = it }<br>)</pre><p>You can think that wherever you see `remember`, it’s business logic.</p><h3>Disadvantages of Mixing Business Logic + UI Logic</h3><p>When everything lives inside composables (without ViewModel), you code becomes:</p><ol><li><strong>Hard to test</strong>: Because they live inside composables. If they were inside ViewModel, you could test them easily.</li><li><strong>Not Scalable</strong>: Today it’s a simple counter, tomorrow you might want to add API calls, validations, complex state, retry logic, error handling. Your compose becomes messy and huge.</li><li><strong>Breaks Separation of Concerns</strong>: In Jetpack Compose or XML Layout they should be for ‘What to show’ not ‘How the system behaves internally’, Right now your composable does both.</li><li><strong>Lifecycle Issues:</strong></li></ol><pre>val list = remember { }</pre><p>remember state:</p><ul><li>Dies if composable leaves composition</li><li>Harder to manage across navigation</li><li>Not shared across screens</li></ul><p>A ViewModel from <strong>Android Jetpack</strong>:</p><ul><li>Survives configuration changes</li><li>Is lifecycle-aware</li><li>Can be shared</li></ul><p>5. <strong>Difficult To Reuse Logic:</strong></p><p>If tomorrow you build:</p><ul><li>Tablet UI</li><li>Web version</li><li>Wear OS version</li></ul><p>You’d have to rewrite logic. With ViewModel, logic is reusable.</p><h4>Current Structure of the App:</h4><pre>Composable<br>    ├── UI logic<br>    ├── Business logic<br>    └── Data mutation</pre><h4>Recommended Structure:</h4><pre>Composable → UI logic<br>ViewModel → Business logic<br>Repository → Data source</pre><blockquote>In this simple example we will not look at Repository but it’s also a important concept.</blockquote><p>When business logic and UI logic live inside composables, the app may work for small demos but quickly becomes hard to test, maintain, and scale. ViewModel enforces separation of concerns by moving state and rules out of the UI layer, allowing composables to remain simple, predictable, and reusable.</p><h3>Here is the code inside MainActivity using a ViewModel:</h3><p><strong>MainActivity</strong>:</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            BasicStateCodelabTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    WellnessScreen()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun WellnessScreen(modifier: Modifier = Modifier, wellnessViewModel: WellnessViewModel = viewModel()) {<br>    Column(modifier = modifier) {<br>        StatefulCounter()<br><br>        WellnessTasksList(list = wellnessViewModel.tasks, onCheckedTask = { task, checked -&gt;<br>            wellnessViewModel.changeTaskChecked(task, checked)<br>        },<br>            onCloseTask = { task -&gt; wellnessViewModel.remove(task) })<br>    }<br>}<br><br>@Composable<br>fun StatefulCounter(modifier: Modifier = Modifier, wellnessViewModel: WellnessViewModel = viewModel()) {<br>    StatelessCounter(wellnessViewModel.count, { wellnessViewModel.increment() }, modifier)<br>}<br><br>@Composable<br>fun StatelessCounter(count: Int, onIncrement: () -&gt; Unit, modifier: Modifier = Modifier) {<br>    Column(modifier = modifier.padding(16.dp)) {<br>        if (count &gt; 0) {<br>            Text(&quot;You&#39;ve had $count glasses.&quot;)<br>        }<br>        Button(onClick = onIncrement, Modifier.padding(top = 8.dp), enabled = count &lt; 10) {<br>            Text(&quot;Add one&quot;)<br>        }<br>    }<br>}<br><br>@Composable<br>fun WellnessTasksList(<br>    list: List&lt;WellnessTask&gt;,<br>    onCheckedTask: (WellnessTask, Boolean) -&gt; Unit,<br>    onCloseTask: (WellnessTask) -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br>    LazyColumn(<br>        modifier = modifier<br>    ) {<br>        items(<br>            items = list,<br>            key = { task -&gt; task.id }<br>        ) { task -&gt;<br>            WellnessTaskItem(<br>                taskName = task.label,<br>                checked = task.checked,<br>                onCheckedChange = { checked -&gt; onCheckedTask(task, checked) },<br>                onClose = { onCloseTask(task) }<br>            )<br>        }<br>    }<br>}<br><br>@Composable<br>fun WellnessTaskItem(<br>    taskName: String,<br>    checked: Boolean,<br>    onCheckedChange: (Boolean) -&gt; Unit,<br>    onClose: () -&gt; Unit,<br>    modifier: Modifier = Modifier<br>) {<br>    Row(<br>        modifier = modifier, verticalAlignment = Alignment.CenterVertically<br>    ) {<br>        Text(<br>            modifier = Modifier<br>                .weight(1f)<br>                .padding(start = 16.dp),<br>            text = taskName<br>        )<br>        Checkbox(<br>            checked = checked,<br>            onCheckedChange = onCheckedChange<br>        )<br>        IconButton(onClick = onClose) {<br>            Icon(Icons.Filled.Close, contentDescription = &quot;Close&quot;)<br>        }<br>    }<br>}</pre><h4>WellnessViewModel.kt</h4><pre>class WellnessViewModel : ViewModel() {<br>    private val _tasks = getWellnessTasks().toMutableStateList()<br>    val tasks: List&lt;WellnessTask&gt;<br>        get() = _tasks<br><br><br>    fun remove(item: WellnessTask) {<br>        _tasks.remove(item)<br>    }<br><br>    fun changeTaskChecked(item: WellnessTask, checked: Boolean) =<br>        _tasks.find { it.id == item.id }?.let { task -&gt;<br>            task.checked = checked<br>        }<br><br>    var count by mutableStateOf(0)<br>        private set<br><br>    fun increment() {<br>        count++<br>    }<br>}<br><br>private fun getWellnessTasks() = List(30) { i -&gt; WellnessTask(i, &quot;Task # $i&quot;) }</pre><h4>Advantages of Using ViewModel</h4><ol><li><strong>Clear Separation of Concerns:</strong></li></ol><ul><li>UI → Displays data</li><li>ViewModel → Manages state + logic</li></ul><pre>fun remove(item: WellnessTask) {<br>    _tasks.remove(item)<br>}<br><br>fun increment() {<br>    count++<br>}</pre><p>These are <strong>business/state logic</strong>, not UI.</p><p><strong>2. Survives Configuration Changes</strong></p><p>ViewModel survives: Screen rotation, Configuration changes.</p><p>Without ViewModel:</p><pre>var count by rememberSaveable { mutableStateOf(0) }</pre><p>This survives rotation but:</p><ul><li>Complex state logic becomes messy</li><li>Hard to scale for larger apps</li></ul><p>With ViewModel:</p><pre>var count by mutableStateOf(0)</pre><p>State survives naturally as long as ViewModel exists.</p><p><strong>3. Easier Testing</strong></p><p><strong>4. Better Scalability: </strong>If you are building a small app both ways works but imagine as you app grows with:</p><ul><li>API calls</li><li>Database</li><li>Pagination</li><li>Error handling</li><li>Loading states</li><li>Complex validation</li></ul><p>Without ViewModel: UI becomes huge and messy.</p><p>With ViewModel: You scale cleanly.</p><p>5. <strong>Reusability</strong></p><p>With ViewModel:</p><ul><li>Multiple screens can share same logic.</li><li>Logic is reusable outside Compose UI.</li></ul><p>Without ViewModel:</p><ul><li>Logic tightly coupled to Composables.</li></ul><p><strong>6. Cleaner Composables</strong></p><p>Look at the improved WellnessTaskItem:</p><pre>@Composable<br>fun WellnessTaskItem(<br> taskName: String,<br> checked: Boolean,<br> onCheckedChange: (Boolean) -&gt; Unit,<br> onClose: () -&gt; Unit,<br>)</pre><p>This is now:</p><p>1. Stateless<br>2. Reusable<br>3. Pure UI<br>4. Predictable</p><p>This is how Compose is designed to work.</p><p><strong>7. Single Source of Truth</strong></p><p>In ViewModel version:</p><pre>ViewModel → holds state<br>UI → reads state<br>UI → sends events<br>ViewModel → updates state</pre><p>This is unidirectional data flow.</p><h4>Mental Model:</h4><p>Think of it like this:</p><p>Without ViewModel → The painter is also thinking and deciding everything.</p><p>With ViewModel → The brain decides, the painter just paints.</p><p>Check out the exact app that I have shown in this example in my <a href="https://github.com/animeshroydev/BasicStateCodelab">Github Repo</a>. You can switch between main (using ViewModel) and without-view-model branch to compare both versions.</p><h3>Conclusion</h3><p>Separating your business logic from your UI isn’t just “architectural purity” it’s future-you protection. Your future self will thank you when you’re not debugging a 500-line Composable at 2 AM wondering why a checkbox broke your entire app. 😂</p><p>Keep your UI pretty. Keep your logic smart. Let them live separate, peaceful lives.</p><p>If this saved you from committing architectural crimes, give it a clap and follow me on Medium. I promise more clean code… and fewer 2 AM debugging sessions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6cbe74bcf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Landscape Screen in Jetpack Compose?]]></title>
            <link>https://medium.com/@droiddev5911/how-to-create-a-landscape-screen-in-jetpack-compose-9a134343467c?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a134343467c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 14:09:44 GMT</pubDate>
            <atom:updated>2026-02-18T14:09:44.140Z</atom:updated>
            <content:encoded><![CDATA[<p>In Jetpack Compose, handling landscape layouts is straightforward once you understand how to detect orientation and design adaptive UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PZCodpQfdfadj91wAsjLA.png" /></figure><p>There are a few ways to achieve this.</p><h4>1. Detect Screen Orientation in Compose</h4><p>The easiest way to detect orientation is by using LocalConfiguration.</p><pre>@Composable<br>fun MyScreen() {<br>    val configuration = LocalConfiguration.current<br><br>    if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {<br>        LandscapeLayout()<br>    } else {<br>        PortraitLayout()<br>    }<br>}</pre><p>This lets you switch layouts dynamically based on orientation.</p><h4>2. Using window size class</h4><p>To do this, use the <a href="https://developer.android.com/reference/kotlin/androidx/compose/material3/windowsizeclass/package-summary#calculateWindowSizeClass(android.app.Activity)">calculateWindowSizeClass()</a> function to see what configuration the phone is in.</p><p>There are three window size class widths: <strong>Compact</strong>, <strong>Medium</strong> and <strong>Expanded</strong>. When the app is in portrait mode it is Compact width, when it is in landscape mode it is Expanded width.</p><pre>import androidx.compose.material3.windowsizeclass.WindowSizeClass<br>import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass<br><br>@Composable<br>fun MySootheApp(windowSize: WindowSizeClass) {<br>   when (windowSize.widthSizeClass) {<br>       WindowWidthSizeClass.Compact -&gt; {<br>           MySootheAppPortrait()<br>       }<br>       WindowWidthSizeClass.Expanded -&gt; {<br>           MySootheAppLandscape()<br>       }<br>   }<br>}</pre><p>Since calculateWindowSize() is still experimental you will need to opt into the ExperimentalMaterial3WindowSizeClassApi class.</p><pre>import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi<br>import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass<br><br>class MainActivity : ComponentActivity() {<br>   @OptIn(ExperimentalMaterial3WindowSizeClassApi::class)<br>   override fun onCreate(savedInstanceState: Bundle?) {<br>       super.onCreate(savedInstanceState)<br>       setContent {<br>           val windowSizeClass = calculateWindowSizeClass(this)<br>           MySootheApp(windowSizeClass)<br>       }<br>   }<br>}</pre><h3>Conclusion</h3><p>Creating a landscape screen in Jetpack Compose is not about forcing rotation: it’s about <strong>designing adaptive UI that responds intelligently to available space</strong>.</p><p>You’ve seen two clean approaches:</p><ul><li><strong>Using </strong><strong>LocalConfiguration</strong> for simple orientation-based switching between portrait and landscape layouts.</li><li><strong>Using </strong><strong>WindowSizeClass</strong> for a more scalable and modern solution that adapts based on screen width (Compact, Medium, Expanded).</li></ul><p>While orientation detection works well for basic use cases, <strong>Window Size Classes are the recommended long-term approach</strong>, especially for tablets, foldables, and larger devices. They allow your UI to scale beyond just portrait vs landscape and move toward true responsive design.</p><p>The key takeaway is this:</p><blockquote><em>In Compose, UI should respond to screen size, not just rotation.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a134343467c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slot-Based Layout in Jetpack Compose: Build Flexible & Reusable UI Like a Pro ]]></title>
            <link>https://medium.com/@droiddev5911/slot-based-layout-in-jetpack-compose-build-flexible-reusable-ui-like-a-pro-0751b8c90759?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0751b8c90759</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 18:44:30 GMT</pubDate>
            <atom:updated>2026-02-14T18:44:30.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umT6LzffJNfU1cxB_CUpkw.png" /></figure><p>A <strong>slot-based layout</strong> is a design pattern where a composable accepts other composables as parameters. Instead of hardcoding UI inside a component, you pass content into it.</p><p>If you’re learning Jetpack Compose deeply (not just using it), then <strong>slot-based layout</strong> is something you must understand.</p><h4>In simple terms:</h4><p>A slot is just a @Composable lambda parameter.</p><h3>Let’s clear some Kotlin concepts first:</h3><h4>What is Lambda?</h4><p>In Kotlin, a <strong>lambda expression</strong> is a concise way to define an anonymous function (a function without a name) that can be treated as a value: stored in variables, passed as arguments to other functions, or returned from them.</p><pre>// Full syntax example: a lambda that takes two Int parameters and returns their sum<br>val sum: (Int, Int) -&gt; Int = { x: Int, y: Int -&gt; x + y }</pre><h4>What is Trailing Lambda?</h4><p>A <strong>trailing lambda</strong> is a syntax convention that allows you to place a lambda expression outside of the parentheses of a function call if it is the function’s last argument.</p><p>Trailing lambda is just Kotlin syntax.</p><p>Instead of writing:</p><pre>Scaffold(<br> content = { padding -&gt; ScreenContent(padding) }<br>)</pre><p>You can write:</p><pre>Scaffold { padding -&gt;<br> ScreenContent(padding)<br>}</pre><p>This is commonly used with collection functions like map, filter, and forEach.</p><pre>numbers.forEach {<br> println(it)<br>}</pre><h4>What is a Higher Order Function?</h4><p>A <strong>higher-order function</strong> in Kotlin is a function that either accepts one or more functions as parameters, returns a function, or both. This capability stems from Kotlin treating functions as “first-class citizens,” meaning they can be handled like any other data type (such as integers or strings).</p><p>Here is a simple example of a higher-order function that takes an operation function as a parameter:</p><pre>fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -&gt; Int): Int {<br> return operation(a, b)<br>}<br><br>fun main() {<br><br> // Calling the higher-order function with a lambda for addition<br> val sum = operateOnNumbers(5, 3) { num1, num2 -&gt; num1 + num2 }<br> println(“The sum is: $sum”) // Output: The sum is: 8<br><br>// Calling the higher-order function with a lambda for multiplication<br> val product = operateOnNumbers(5, 3) { num1, num2 -&gt; num1 * num2 }<br> println(“The product is: $product”) // Output: The product is: 15<br><br>}</pre><h3>Let’s come to the Slot-based Layout</h3><p>When I first started with Compose, I used ready-made composables like Card, Scaffold, TopAppBar. But later I realized something powerful:</p><p>Compose components are flexible because they use <strong>slots</strong>.</p><h4>What is Slot-Based Layout?</h4><p>As I already mentioned in the beginning, a <strong>slot-based layout</strong> is a design pattern where a composable accepts other composables as parameters.</p><p>Real Example: Scaffold Uses Slots, If you’ve used Scaffold, you’ve already used slot APIs.</p><pre>Scaffold(<br> topBar = { MyTopBar() },<br> floatingActionButton = { MyFab() }<br>) { padding -&gt;<br> ScreenContent(padding)<br>}</pre><p>Here:</p><ul><li>topBar is a slot</li><li>floatingActionButton is a slot</li><li>The trailing lambda { padding -&gt; } is the main content slot</li></ul><p>Compose gives you a <strong>structure</strong>, and you inject your UI into defined areas.</p><h4>Why Slot-Based Layout is Powerful:</h4><ol><li>Reusability: You don’t fix content inside the component.</li><li>Flexibility: The parent decides what UI to inject.</li><li>Clean Architecture: Encourages separation of structure and content.</li></ol><h3>We can also Create Your Own Slot-Based Layout</h3><p>Let’s build a reusable CustomCard.</p><h4>Bad Approach (Hardcoded)</h4><pre>@Composable<br>fun CustomCard() {<br> Card {<br> Column {<br> Text(“Title”)<br> Text(“Description”)<br>    }<br>  }<br>}</pre><p>This is rigid. You can’t reuse it easily.</p><h4>Slot-Based Approach</h4><pre>@Composable<br>fun CustomCard(<br>    header: @Composable () -&gt; Unit,<br>    content: @Composable () -&gt; Unit<br>) {<br>    Card {<br>        Column {<br>            header()<br>            Spacer(modifier = Modifier.height(8.dp))<br>            content()<br>        }<br>    }<br>}</pre><pre>// Usage<br><br>CustomCard(<br>    header = { Text(&quot;My Title&quot;) },<br>    content = { Text(&quot;This is description&quot;) }<br>)</pre><p>Now your card works with:</p><ul><li>Text</li><li>Images</li><li>Buttons</li><li>Entire layouts</li></ul><p>That’s flexibility.</p><h4>Multiple Slots Example</h4><pre>@Composable<br>fun ProfileLayout(<br>    avatar: @Composable () -&gt; Unit,<br>    name: @Composable () -&gt; Unit,<br>    actions: @Composable () -&gt; Unit<br>) {<br>    Row(<br>        verticalAlignment = Alignment.CenterVertically<br>    ) {<br>        avatar()<br>        Column(modifier = Modifier.weight(1f)) {<br>            name()<br>        }<br>        actions()<br>    }<br>}</pre><pre>// Usage<br>ProfileLayout(<br>    avatar = { Image(...) },<br>    name = { Text(&quot;Animesh Roy&quot;) },<br>    actions = { IconButton(...) }<br>)</pre><p>Now this layout is reusable across:</p><ul><li>User list</li><li>Chat screen</li><li>Comment section</li><li>Profile page</li></ul><h4>Real-World Compose Components That Use Slots</h4><ul><li>Scaffold</li><li>AlertDialog</li><li>TopAppBar</li><li>TabRow</li><li>NavigationBar</li></ul><p>That’s why Compose feels modular.</p><h4>Simple One Liner</h4><p>Slot-based layout in Compose is a pattern where composables accept other composables as parameters to create flexible, reusable, and scalable UI components.</p><h4>Let&#39;s look at an example from Android Compose Codelabs:</h4><p>Section 9: <a href="https://developer.android.com/codelabs/jetpack-compose-layouts?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fjetpack-compose-for-android-developers-1%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fjetpack-compose-layouts#8">Home Section Slot API</a></p><h4>Here is the MySoothe App home screen:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ZL03ctrIiBS9xUFYHcm68A.png" /></figure><p>There are multiple sections that follow the same pattern. They each have a title, with some content varying depending on the section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*bkqW7NVOeKnCr902WT7kCQ.png" /></figure><p>As you can see, each section has a title and a slot. The title has some spacing and style information associated with it. The slot can be filled in dynamically with different content, depending on the section.</p><p>To implement this flexible section container, you use <em>slot APIs</em>.</p><p>Slot-based layouts leave an empty space in the UI for the developer to fill as they wish. You can use them to create more flexible layouts.</p><p>We will adapt the HomeSection composable to receive the title and slot content.</p><pre>@Composable<br>fun HomeSection(<br>   @StringRes title: Int,<br>   modifier: Modifier = Modifier,<br>   content: @Composable () -&gt; Unit<br>) {<br>   Column(modifier) {<br>       Text(<br>           text = stringResource(title),<br>           style = MaterialTheme.typography.titleMedium,<br>           modifier = Modifier<br>               .paddingFromBaseline(top = 40.dp, bottom = 16.dp)<br>               .padding(horizontal = 16.dp)<br>       )<br>       content()<br>   }<br>}<br><br>@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)<br>@Composable<br>fun HomeSectionPreview() {<br>   MySootheTheme {<br>       HomeSection(R.string.align_your_body) {<br>           AlignYourBodyRow()<br>       }<br>   }<br>}</pre><p>You can use the content parameter for the composable&#39;s slot. This way, when you use the HomeSection composable, you can use a trailing lambda to fill the content slot.</p><p>Let’s reuse it to make it look like the Screenshot:</p><pre>@Composable<br>fun MySootheApp() {<br><br><br>    Column {<br><br>        SearchBar(modifier = Modifier.padding(8.dp))<br><br>       <br>        HomeSection(R.string.align_your_body) {<br>            AlignYourBodyRow()<br>        }<br>        // Reusing using Slot Layout, style of text applied dynamically<br>        HomeSection(R.string.favorite_collections) {<br>            FavoriteCollectionsGrid()<br>        }<br><br>    }<br>}</pre><p>Slot-based layouts are one of the key ideas that make UI development in Jetpack Compose flexible and scalable. By passing composable lambdas instead of fixed content, you separate structure from UI, making components easier to reuse, customize, and maintain. Whether you’re building simple reusable cards or complex screens like dashboards and profiles, understanding slots helps you design cleaner APIs and more modular code. As your apps grow, this pattern becomes especially valuable, allowing you to build UI components that adapt to different needs without rewriting layouts.</p><p>For more information on Slot API, visit the <a href="https://developer.android.com/develop/ui/compose/layouts/basics#slot-based-layouts">official docs</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0751b8c90759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Variance in Kotlin: Covariance, Invariance & Contravariance Made Simple]]></title>
            <link>https://medium.com/@droiddev5911/mastering-variance-in-kotlin-covariance-invariance-contravariance-made-simple-3c4216075c1f?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c4216075c1f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[variance]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 11:34:20 GMT</pubDate>
            <atom:updated>2026-02-12T11:34:20.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxSxFUiQ_2tmup0XvolK5g.png" /></figure><p>When learning Kotlin generics, many developers get confused by terms like <strong>variance</strong>, <strong>invariant</strong>, <strong>covariance</strong>, and <strong>contravariance</strong>. These sound complex at first, but once you understand the idea behind them, they become simple and extremely useful, especially in Android development.</p><h3>What Is Variance?</h3><p>Variance defines <strong>how generic types behave in relation to inheritance</strong>.</p><p>Let’s look at an Example:</p><pre>// This code works fine<br>fun main() {<br><br>    val shortList: List&lt;Short&gt; = listOf(1,2,3,4,5)<br><br>    /*<br>      Because short extends Number<br>    * We can pass List&lt;Short&gt; to<br>    * List&lt;Number&gt;<br>    *  <br>    */<br><br>    convertToInt(shortList)<br><br>}<br><br>fun convertToInt(collection: List&lt;Number&gt;) {<br>    for (num in collection) {<br>        println(&quot;${num.toInt()}&quot;)<br>    }<br>}<br><br>// This code gives error<br>fun main() {<br><br>    val shortList: MutableList&lt;Short&gt; = mutableListOf(1,2,3,4,5)<br><br>    /* Because short extends Number<br>    * We can pass List&lt;Short&gt; to<br>    * List&lt;Number&gt;<br>    *  */<br><br>    convertToInt(shortList) // error<br><br>}<br><br>fun convertToInt(collection: MutableList&lt;Number&gt;) {<br>    for (num in collection) {<br>        println(&quot;${num.toInt()}&quot;)<br>    }<br>}</pre><p>You might ask:</p><ol><li>Why this second code gives error, Shorts are number too?</li><li>This works in the case of immutable list but why not with working with the mutable list?</li></ol><p>When we are discussing generics, using type and subtype is more accurate than using class and subclass, for example, List is a class, it isn’t a type but List&lt;String&gt; is a type so as List&lt;Int&gt;, List&lt;Short&gt; is a subtype of List&lt;Number&gt; becuase List&lt;Int&gt; is not a subclass of List&lt;Number&gt;, we aren’t extending anything. It’s saying a List&lt;Number&gt; should be able to accept List&lt;Int&gt;</p><p>Hope you understand the difference between subclass and subtype now.</p><p>Let’s find out now why our second version of code is giving an error.</p><p>In our case, we know that Short is a subclass of Number, but is Short a subtype of Number?</p><p>The same goes for super type: List&lt;Number&gt; is super type of List&lt;Short&gt;</p><p>This brings us to what we called covariance, what we want to do here is we want to treat a List&lt;Short&gt; like a List&lt;Number&gt; and we were able to do that when we were using an immutable list val shortList: List&lt;Short&gt; = listOf(1,2,3,4,5)</p><p>What we are saying is we want List&lt;Short&gt; to be a subtype of List&lt;Number&gt;, and if we want the subtyping to be preserved when working with generics, we have to declare the type parameter to be covariant.</p><h4>The collection interface was covariant, but the mutable collection interface is not covariant. That’s why we are getting an error here.</h4><p>If we want MutableList&lt;Short&gt; to be treated like a MutableList&lt;Number&gt;, then MutableList&lt;Short&gt; has to be a subtype of MutableList&lt;Number&gt;, and if we want subtyping to be preserved, we have to declare the parameter to be covariant.</p><p>Hope now you are getting why this works with the immutable list rather than the mutable list.</p><p>Immutable list is covariant and mutable is not covariant, when we are dealing with covariant, the subtyping is preserved.</p><p>To preserve the subtyping and get rid of errors, we can do something like this:</p><pre>fun convertToInt(collection: MutableList&lt;out Number&gt;)</pre><p>What the above code is doing is using <strong>covariance with </strong><strong>out</strong> in a <strong>type projection</strong>. A mutable list of some type that is a subtype of Number, but we don’t know exactly which one.</p><h4>Let’s look at another Example:</h4><pre>fun main() {<br><br><br>}<br><br>fun tendGarden(roseGarden: Garden&lt;Rose&gt;) {<br>    waterGarden(roseGarden) // This lines gives error, similar to above example<br>}<br><br>fun waterGarden(garden: Garden&lt;Flower&gt;) {<br><br>}<br><br>open class Flower {<br><br>}<br><br>class Rose: Flower() {<br><br>}<br><br>class Garden&lt;T: Flower&gt; {<br><br>}</pre><p>Error says waterGarden function wants a Garden&lt;Flower&gt;, but we are passing Garden&lt;Rose&gt; and we know Rose is a subclass of Flower. This is happening because Garden class is <strong>invariant</strong>. Therefore when we ask for garden of flower we can only provides garden of flower. Because this is invariant, class Garden&lt;T: Flower&gt; this will only accept garden of flower. It will not accept the Garden of Rose. In other word subtyping is not preserved meas invariant.</p><p>We want Garden to accept a type of Flower and all of the subtypes. To do so we have to make Garden covariant, to do that we need to add out keyword.</p><pre>class Garden&lt;out T: Flower&gt; {<br><br>}</pre><p>Let’s talk about what is <strong>in</strong> and <strong>out </strong>position in Kotlin:</p><ul><li>Function parameters are considered to be <strong>in</strong> position.</li><li>Function return type is <strong>out</strong> position.</li></ul><h4>Let’s look at another example:</h4><pre>class Garden&lt;out T: Flower&gt; {<br>    <br>    val flowers: List&lt;T&gt; = listOf()<br>    <br>    fun pickFlower(i: Int): T = flowers[i]<br>    <br>    fun plantFlower(flower: T) { // T gives error<br><br>     /* error message:<br>     Type parameter &#39;T&#39; is declared as &#39;out&#39; but occurs in &#39;in&#39; <br>     position in type &#39;T (of class Garden&lt;out T : Flower&gt;)&#39;.<br>     */<br>        <br>    }<br>    <br>}</pre><p>Basically error says we can use it as a return type inside a member, but we can no longer use it as a parameter type. We can pick flower but we can’t plant them.</p><p>So when a class is covariant, meaning that we use the out keyword means subtyping is preserved and the class can only be used in the out position(can return not accept).</p><p>Crystal clear example:</p><pre>fun pickFlower(i: Int): T = flowers[i] // returning means out position<br><br>// accepting as parameter means in position<br>fun plantFlower(flower: T) { // T gives error<br><br>     /* error message:<br>     Type parameter &#39;T&#39; is declared as &#39;out&#39; but occurs in &#39;in&#39; <br>     position in type &#39;T (of class Garden&lt;out T : Flower&gt;)&#39;.<br>     */<br>        <br>    }</pre><p>You might say we are using in position here:</p><pre>fun tendGarden(roseGarden: Garden&lt;Rose&gt;) {<br>    waterGarden(roseGarden)<br>}</pre><p>When we are talking about in and out position, we are talking about the member function of the class Garden.</p><p>That’s covariance. We use covariance when we want subtyping to be preserved, so we can pass the instance of the type or the subtype.</p><p>Here’s a <strong>clear FAQ-style guide</strong> you can even use in a blog or notes.</p><h3>mutableListOf vs listOf in Kotlin (Covariance FAQ)</h3><p>FAQ 1: What is the basic difference between listOf() and mutableListOf()?</p><p><strong>listOf()</strong></p><ul><li>Returns a <strong>read-only List</strong></li><li>You cannot add or remove elements</li><li>Covariant (List&lt;out T&gt;)</li></ul><p><strong>mutableListOf()</strong></p><ul><li>Returns a <strong>MutableList</strong></li><li>You can add, remove, or modify elements</li><li>Invariant (MutableList&lt;T&gt;)</li></ul><pre>val list = listOf(1, 2, 3) // Read-only<br>val mutable = mutableListOf(1, 2, 3) // Read-write</pre><p>FAQ 2: Why is List covariant?</p><pre>interface List&lt;out E&gt;</pre><p>Because List only <strong>produces values</strong> and does not allow adding items.</p><pre>val ints: List&lt;Int&gt; = listOf(1, 2, 3)<br>val numbers: List&lt;Number&gt; = ints // Works</pre><p>This is safe because we only read values.</p><p>FAQ 3: Why is MutableList NOT covariant?</p><pre>interface MutableList&lt;E&gt;</pre><p>It allows:</p><ul><li>Reading</li><li>Writing</li></ul><p>If Kotlin allowed covariance here:</p><pre>val cats: MutableList&lt;Cat&gt; = mutableListOf()<br>val animals: MutableList&lt;Animal&gt; = cats // Dangerous!<br>animals.add(Dog()) // Breaks type safety</pre><p>Now the cat list contains a dog, unsafe.</p><p>So Kotlin prevents this.</p><h3>One-Line Summary</h3><p>List is covariant and safe for reading and sharing data.<br>MutableList is invariant because writing data must remain type-safe.</p><ul><li><strong>Covariant</strong> → Subtypes are allowed (read-only safe)</li><li><strong>Invariant</strong> → No subtype relationship (read + write unsafe)</li></ul><p>If collection:</p><ul><li>Only gives data → use List (covariant)</li><li>Needs modification → use MutableList (invariant)</li></ul><h4>Covariant ( out )</h4><p>A subtype relationship is preserved.</p><p>If: Cat is a subtype of Animal</p><p>Then: Box&lt;Cat&gt; is a subtype of Box&lt;Animal&gt;</p><p>This works in Kotlin when the generic type is marked with out.</p><p>Example:</p><pre>val cats: List&lt;Cat&gt; = listOf()<br>val animals: List&lt;Animal&gt; = cats // ✅ Allowed (List is covariant)</pre><p>Why safe?<br> Because you can <strong>only read</strong> from it, not add.</p><h4>Invariant</h4><p>No subtype relationship is allowed.</p><p>Even if: Cat is a subtype of Animal</p><p>This does NOT work: Box&lt;Cat&gt; is NOT a subtype of Box&lt;Animal&gt;</p><pre>val cats: MutableList&lt;Cat&gt; = mutableListOf()<br>val animals: MutableList&lt;Animal&gt; = cats // ❌ Error</pre><p>Why?<br> Because you can add wrong types and break safety.</p><h4>Contravariant ( in )</h4><p>if: Cat is a subtype of Animal</p><p>Then in contravariance: Printer&lt;Animal&gt; can be used where Printer&lt;Cat&gt; is expected.</p><p>Why does this work?</p><p>Because a contravariant class <strong>consumes</strong> values (takes input), it does not produce them.</p><p>Example:</p><pre>class Printer&lt;in T&gt; {<br> fun print(item: T) {<br> println(item)<br> }<br>}</pre><p>Usage:</p><pre>val animalPrinter: Printer&lt;Animal&gt; = Printer()<br>val catPrinter: Printer&lt;Cat&gt; = animalPrinter // ✅ Allowed<br>catPrinter.print(Cat())</pre><p>Why safe?</p><p>If something can handle <strong>any Animal</strong>, it can definitely handle a <strong>Cat</strong>.</p><h4>One-Line Rule</h4><p><strong>Contravariant (</strong><strong>in) = Consumer (takes values, doesn’t return them).</strong></p><p>out gives data, in takes data.</p><h3>Wrap Up</h3><ul><li><strong>Covariant (</strong><strong>out)</strong> is used when a class or function <strong>only returns data</strong> (producer).</li><li><strong>Contravariant (</strong><strong>in)</strong> is used when a class or function <strong>only accepts data</strong> (consumer).</li><li><strong>Invariant</strong> is used when a class <strong>both reads and writes data</strong>, so type safety must be strict.</li></ul><h3>Where you mostly see this in Android</h3><ol><li><strong>Collections</strong></li></ol><ul><li>List&lt;out T&gt; is covariant because it’s read-only.</li><li>MutableList&lt;T&gt; is invariant because you can add and remove items.</li></ul><p><strong>2. RecyclerView / Adapters</strong></p><ul><li>Generic adapters sometimes use variance to handle different model types safely.</li></ul><p><strong>3. Coroutines &amp; Flow</strong></p><ul><li>Flow&lt;out T&gt; is covariant since it emits values (produces data).</li></ul><p><strong>4. Callbacks / Interfaces</strong></p><ul><li>Listener or handler interfaces often use in because they consume objects.</li></ul><h3>One-line memory rule</h3><p><strong>Producer = </strong><strong>out (covariant)</strong><br><strong>Consumer = </strong><strong>in (contravariant)</strong><br><strong>Read + Write = invariant</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c4216075c1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enums vs Sealed Classes in Android (Kotlin): When to Use What?]]></title>
            <link>https://medium.com/@droiddev5911/enums-vs-sealed-classes-in-android-kotlin-when-to-use-what-513c761edfaf?source=rss-5caf11458b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/513c761edfaf</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Animesh]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 15:00:33 GMT</pubDate>
            <atom:updated>2026-02-12T03:54:18.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOfQwcCFcOCq-4nXXdIajA.png" /></figure><p>A few days back, I was just brushing up on my Kotlin fundamentals, and this question came to my mind: why sealed class over enums? Let’s go deep into this topic.</p><p><strong>Should I use an enum or a sealed class?</strong></p><p>At first, both may seem similar because they help represent a <strong>fixed set of types</strong>. But in real Android projects, especially with <strong>UI states, error handling, network responses, and architecture patterns, </strong>choosing the right one makes your code cleaner, safer, and easier to maintain.</p><h4><strong>What is an Enum?</strong></h4><p>An <strong>enum (enumeration)</strong> represents a <strong>fixed set of constants</strong>. Each value is usually simple and similar in structure.</p><p>Example:</p><pre>enum class NetworkStatus {<br> LOADING,<br> SUCCESS,<br> ERROR<br>}</pre><p>Usage:</p><pre>when (status) {<br> NetworkStatus.LOADING -&gt; showLoading()<br> NetworkStatus.SUCCESS -&gt; showData()<br> NetworkStatus.ERROR -&gt; showError()<br>}</pre><p>Enums are simple, lightweight, and ideal when values are just labels or constants.</p><h4><strong>What is a Sealed Class?</strong></h4><p>A sealed class represents a restricted hierarchy of classes where each subclass can hold different types of data.</p><pre>sealed class UiState {<br><br>    object Loading : UiState()<br><br>    data class Success(val data: List&lt;String&gt;) : UiState()<br><br>    data class Error(val message: String) : UiState()<br>}</pre><p>Usage:</p><pre>when (state) {<br> is UiState.Loading -&gt; showLoading()<br> is UiState.Success -&gt; showData(state.data)<br> is UiState.Error -&gt; showError(state.message)<br>}</pre><p>Sealed classes are more flexible, can store different data, great for UI state management.</p><p>Real Android Examples:</p><p>Theme Mode:</p><pre>enum class ThemeMode {<br> LIGHT,<br> DARK,<br> SYSTEM<br>}</pre><p>Sort Order:</p><pre>enum class SortOrder {<br> ASCENDING,<br> DESCENDING<br>}</pre><p><strong>3. Days of week, categories, or fixed labels, etc…</strong></p><p>Enums are perfect when you only need <strong>names</strong>, not behavior or data.</p><h3>When to Use Sealed Class in Android</h3><p>Use sealed classes when:</p><ol><li>Each state needs <strong>different data</strong></li><li>You are handling <strong>UI states</strong></li><li>Working with <strong>network responses</strong></li><li>Using <strong>MVI / MVVM architecture</strong></li></ol><h4>Real Android Example:</h4><h4>Api Response:</h4><pre>sealed class ApiResult&lt;T&gt; {<br> object Loading : ApiResult&lt;Nothing&gt;()<br> data class Success&lt;T&gt;(val data: T) : ApiResult&lt;T&gt;()<br> data class Error(val message: String) : ApiResult&lt;Nothing&gt;()<br>}</pre><p>This is very common in Android apps.</p><h4>Navigation Events</h4><pre>sealed class NavigationEvent {<br> object NavigateToHome : NavigationEvent()<br> data class NavigateToDetails(val id: Int) : NavigationEvent()<br>}<br>// Enums cannot carry parameters like id.</pre><h3>What Most Android Developers Do in Practice</h3><p>In modern Android:</p><ul><li>Enums → Configuration values, modes, categories</li><li>Sealed classes → UI state, API state, navigation, events</li></ul><h3>FAQ:</h3><h3>Instead of using sealed keyword if we use open Will it work fine?</h3><p>Answer: Yes, it <strong>will work</strong>, but it <strong>won’t give you the same safety and benefits</strong> that it sealed provides. That difference is very important in Android apps.</p><p>Here is what you said:</p><pre>open class UiState {<br><br>    object Loading : UiState()<br><br>    data class Success(val data: List&lt;String&gt;) : UiState()<br><br>    data class Error(val message: String) : UiState()<br>}</pre><p>This code <strong>compiles and runs fine</strong>. So technically, yes — it works.</p><p>But there are important differences.</p><h4>Problem 1: No Exhaustive when Checking</h4><p>With a <strong>sealed class</strong>, Kotlin knows all subclasses at compile time.</p><p>So this works without else:</p><pre>when (state) {<br> is UiState.Loading -&gt; {}<br> is UiState.Success -&gt; {}<br> is UiState.Error -&gt; {}<br>}</pre><p>But with an <strong>open class</strong>, Kotlin <strong>cannot guarantee</strong> these are all the subclasses.</p><pre>when (state) {<br> is UiState.Loading -&gt; {}<br> is UiState.Success -&gt; {}<br> is UiState.Error -&gt; {}<br> else -&gt; {} // Required<br>}</pre><p>Why? Because someone could create:</p><pre>class EmptyState : UiState()</pre><p>And your when would break. This is dangerous in UI state handling.</p><h4>Problem 2: Anyone Can Extend It Anywhere</h4><p>With open, Subclasses can be created in <strong>any file or module</strong>. With sealed, subclasses must be in the <strong>same file (or same package depending on Kotlin version)</strong>. That restriction is intentional, it protects your architecture.</p><h4>Problem 3: UI State Becomes Unpredictable</h4><p>In Android (especially MVVM or MVI), we usually want: Loading, Success, Error, and nothing else.</p><p>Sealed classes guarantee that. Open classes do not.</p><h4>Let’s look at a <strong>real-world Android scenario</strong> where <strong>enum starts failing</strong> and <strong>sealed class becomes the correct solution</strong>.</h4><h3>Example: Loading Data in a ViewModel</h3><p>Imagine:</p><ul><li>You call an API</li><li>UI must react to states</li></ul><p>Typical states:</p><ul><li>Loading</li><li>Success (with data)</li><li>Error (with message)</li></ul><p>First Attempt (using Enums, where it fails)</p><p>Enum</p><pre>enum class UiState {<br> LOADING,<br> SUCCESS,<br> ERROR<br>}</pre><p>ViewModel</p><pre>class MainViewModel : ViewModel() {<br><br>    var state = MutableLiveData&lt;UiState&gt;()<br><br>    fun loadUsers() {<br>        state.value = UiState.LOADING<br><br>        // pretend API call<br>        state.value = UiState.SUCCESS<br>    }<br>}</pre><h3>The Problem</h3><p>Where do we store:</p><ul><li>User list?</li><li>Error message?</li></ul><p>You end up doing this:</p><pre>class MainViewModel : ViewModel() {<br><br> val state = MutableLiveData&lt;UiState&gt;()<br> val users = MutableLiveData&lt;List&lt;String&gt;&gt;()<br> val errorMessage = MutableLiveData&lt;String&gt;()<br><br>}</pre><p>Now your state is <strong>spread across multiple variables</strong>.</p><p>This creates issues:</p><ul><li>UI must observe multiple LiveData</li><li>Harder to maintain</li><li>Easy to introduce bugs</li></ul><p>This is why enum becomes weak here.</p><h3>Correct Approach: Using Sealed Class</h3><p>Now everything stays in one place.</p><pre>sealed class UiState {<br><br>    object Loading : UiState()<br><br>    data class Success(val users: List&lt;String&gt;) : UiState()<br><br>    data class Error(val message: String) : UiState()<br>}</pre><p>ViewModel</p><pre>class MainViewModel : ViewModel() {<br><br>val state = MutableLiveData&lt;UiState&gt;()<br><br>fun loadUsers() {<br> state.value = UiState.Loading<br><br>// simulate API response<br> val users = listOf(“John”, “Alice”, “David”)<br><br>state.value = UiState.Success(users)<br> <br>  }<br>}</pre><h3>Activity / Fragment</h3><pre>viewModel.state.observe(this) { state -&gt;<br><br>    when (state) {<br><br>        is UiState.Loading -&gt; showLoading()<br><br>        is UiState.Success -&gt; showUsers(state.users)<br><br>        is UiState.Error -&gt; showError(state.message)<br>    }<br>}</pre><h3>Why This Is Better</h3><p>Now:</p><ul><li>One state variable</li><li>UI logic is clean</li><li>Compiler guarantees all cases handled</li><li>Easy to extend</li></ul><p>You’ll see this in:</p><ul><li>MVVM</li><li>MVI</li><li>Jetpack Compose</li><li>Production apps</li></ul><h4>Why sealed class over enum for UI state?</h4><p>Because UI states often carry different data, and sealed classes allow type-safe modeling of states while keeping everything in a single observable stream.</p><p>Checkout the WhatsApp Clone App where the <strong>Enums class</strong> is used for items of Tabs Navigation in Jetpack Compose:</p><p><a href="https://github.com/animeshroydev/SampleWhatsAppClone/blob/main/app/src/main/java/com/example/samplewhatsappclone/Tabs.kt">SampleWhatsAppClone/app/src/main/java/com/example/samplewhatsappclone/Tabs.kt at main · animeshroydev/SampleWhatsAppClone</a></p><h3>Wrap Up</h3><p>Both <strong>enums</strong> and <strong>sealed classes</strong> help represent a fixed set of types in Kotlin, but they serve different purposes.</p><p>Use <strong>enums</strong> when you only need simple constant values like modes, categories, or labels. They are lightweight and easy to use.</p><p>Use <strong>sealed classes</strong> when each state needs to carry different data or behavior, such as UI states, API responses, or navigation events in Android.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=513c761edfaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>