<?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 sagar jaulaniya on Medium]]></title>
        <description><![CDATA[Stories by sagar jaulaniya on Medium]]></description>
        <link>https://medium.com/@sagarjaulaniya13591?source=rss-fe105db1af1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-JIRl_FVoY0iN20S5o9A1g.jpeg</url>
            <title>Stories by sagar jaulaniya on Medium</title>
            <link>https://medium.com/@sagarjaulaniya13591?source=rss-fe105db1af1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:47:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sagarjaulaniya13591/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[Understanding Kotlin Scope Functions in Android (Without Memorizing Them)]]></title>
            <link>https://medium.com/@sagarjaulaniya13591/understanding-kotlin-scope-functions-in-android-without-memorizing-them-30fb66514af1?source=rss-fe105db1af1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fb66514af1</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-scope-functions]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[sagar jaulaniya]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 10:23:34 GMT</pubDate>
            <atom:updated>2026-07-21T10:23:34.168Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re learning Kotlin for Android development, you’ve probably come across these five scope functions:</p><ul><li>let</li><li>run</li><li>with</li><li>apply</li><li>also</li></ul><p>And let’s be honest, they can be confusing at first.</p><p>When I started learning Kotlin, I used to memorize their definitions and still got confused during interviews or while writing code. The reality is that you don’t need to memorize them — you just need to understand <strong>when and why</strong> to use them.</p><p>The easiest way to learn scope functions is by thinking about the problem you’re trying to solve.</p><p>Let’s look at them one by one with some real-world Android examples.</p><h4>1. let</h4><p>let is mostly used when working with nullable objects or when you want to perform an operation on an object.</p><pre>val userName: String? = &quot;John Doe&quot;<br><br>userName?.let {<br>    println(&quot;Welcome, $it&quot;)<br>}</pre><h4>Common Android Use Cases</h4><ul><li>Null safety</li><li>Handling API responses</li><li>Working with nullable objects</li></ul><p>For example:</p><pre>response.body()?.let { user -&gt;<br>    updateUI(user)<br>}</pre><blockquote><em>If you&#39;re dealing with a nullable object, </em><em>let is usually the right choice.</em></blockquote><h4>2. run</h4><p>run is useful when you want to perform multiple operations and return a final result.</p><pre>val message = &quot;Android&quot;.run {<br>    uppercase() + &quot; Developer&quot;<br>}<br><br>println(message)</pre><h4>Common Android Use Cases</h4><ul><li>Formatting data</li><li>Calculating values</li><li>Returning a final result</li></ul><p>For example:</p><pre>val fullName = user.run {<br>    &quot;$firstName $lastName&quot;<br>}</pre><p>Think of run as &quot;do some work and give me a result.&quot;</p><h4>3. with</h4><p>with is used when you want to perform multiple operations on the same object.</p><pre>with(binding) {<br>    tvTitle.text = &quot;Scope Functions&quot;<br>    btnLogin.isEnabled = true<br>    progressBar.hide()<br>}</pre><p>Instead of writing:</p><pre>binding.tvTitle.text = &quot;Scope Functions&quot;<br>binding.btnLogin.isEnabled = true<br>binding.progressBar.hide()</pre><p>the code becomes much cleaner and easier to read.</p><h4>Common Android Use Cases</h4><ul><li>View Binding</li><li>Multiple UI updates</li><li>Cleaner code</li></ul><blockquote><em>If you’re working with the same object multiple times, </em><em>with is a great choice.</em></blockquote><h4>4. apply</h4><p>apply is probably one of the most commonly used scope functions in Android development.</p><p>It’s mainly used for object initialization and configuration.</p><pre>val user = User().apply {<br>    name = &quot;Jhon Doe&quot;<br>    age = 27<br>    city = &quot;Jaipur&quot;<br>}</pre><h4>Common Android Use Cases</h4><ul><li>Object initialization</li><li>AlertDialog setup</li><li>RecyclerView adapters</li><li>Retrofit or Room configurations</li></ul><p>Example:</p><pre>val dialog = AlertDialog.Builder(this)<br>    .apply {<br>        setTitle(&quot;Logout&quot;)<br>        setMessage(&quot;Are you sure?&quot;)<br>    }<br>    .create()</pre><blockquote><em>If you&#39;re configuring an object, use </em><em>apply.</em></blockquote><h4>5. also</h4><p>also is used when you want to perform some additional operation without changing the object&#39;s purpose.</p><pre>val user = User().also {<br>    println(&quot;User object created&quot;)<br>}</pre><h4>Common Android Use Cases</h4><ul><li>Logging</li><li>Analytics events</li><li>Debugging</li><li>Side operations</li></ul><p>For example:</p><pre>repository.getUser()<br>    .also {<br>        Log.d(&quot;API&quot;, &quot;User data received&quot;)<br>    }</pre><blockquote><em>Think of </em><em>also as &quot;do something extra and return the same object.&quot;</em></blockquote><h3>The Biggest Difference Between Scope Functions</h3><p>Most developers don’t struggle with writing scope functions. They struggle with understanding two things:</p><ol><li>How is the object accessed?</li><li>What does the function return?</li></ol><p>Let’s simplify both.</p><pre>Object Reference<br><br>Function    | Object Reference<br>--------------------------------<br>let         | it<br>also        | it<br>run         | this<br>with        | this<br>apply       | this</pre><p>If you like writing this, use run, with, or apply.</p><p>If you prefer using it, use let or also.</p><pre>Return Value<br><br>Function    | Returns<br>--------------------------------<br>let         | Lambda result<br>run         | Lambda result<br>with        | Lambda result<br>apply       | Object itself<br>also        | Object itself</pre><p>A simple trick to remember this is:</p><pre>let, run and with<br>↓<br>Return RESULT<br><br>apply and also<br>↓<br>Return OBJECT</pre><p>Trust me, remembering this one line will solve 80% of the confusion around scope functions.</p><h4>Interview Questions That Confuse Most Developers</h4><h4>Q1. What’s the difference between let and run?</h4><p>Both return the lambda result.</p><p>The difference is simply how they refer to the object.</p><pre>val name = &quot;Jhon Doe&quot;<br><br>name.let {<br>    println(it)<br>}<br><br>name.run {<br>    println(this)<br>}</pre><p>Use:</p><ul><li>let for null safety.</li><li>run when you want cleaner access to an object&#39;s members.</li></ul><h4>Q2. What’s the difference between apply and also?</h4><p>This is one of the most common interview questions.</p><pre>val user = User().apply {<br>    name = &quot;Jhon Doe&quot;<br>}</pre><p>vs</p><pre>val user = User().also {<br>    Log.d(&quot;TAG&quot;, &quot;User created&quot;)<br>}</pre><p>The easiest way to remember it is:</p><pre>apply -&gt; Configure the object.<br><br>also -&gt; Perform an extra operation.</pre><p>If you&#39;re initializing an object, go with apply.</p><p>If you&#39;re logging, debugging, or doing something extra, use also.</p><h4>Q3. What’s the difference between run and with?</h4><p>Surprisingly, they’re very similar.</p><pre>user.run {<br>    println(name)<br>}</pre><pre>with(user) {<br>    println(name)<br>}</pre><p>The difference is:</p><pre>run -&gt; Extension function<br><br>with -&gt; Normal function</pre><p>You call run on an object:</p><pre>user.run { }</pre><p>while with takes the object as an argument:</p><pre>with(user) { }</pre><p>In Android projects, you’ll frequently see:</p><pre>with(binding) {<br>    ...<br>}</pre><p>for updating multiple UI components.</p><h4>Which Scope Functions Are Used the Most in Android?</h4><p>From day-to-day Android development, these are the ones you’ll probably use the most:</p><pre>Scope Function | Common Usage<br>--------------------------------------------------------<br>let            | Null safety and API responses<br>run            | Calculating and returning values<br>with           | Working with the same object multiple times<br>apply          | Object initialization and configuration<br>also           | Logging, debugging, and side operations</pre><pre>response.body()?.let { }<br><br>User().apply { }<br><br>with(binding) { }<br><br>repository.getUser().also { }<br><br>user.run { }</pre><h4>My Simple Trick to Remember Them</h4><p>Whenever I’m confused, I ask myself these questions:</p><p>Do I want to return the object?</p><pre>Yes<br>↓<br>apply or also</pre><p>Do I want to return a result?</p><pre>Yes<br>↓<br>let, run or with</pre><p>Am I configuring an object?</p><pre>Yes<br>↓<br>apply</pre><p>Am I dealing with null safety?</p><pre>Yes<br>↓<br>let</pre><p>Am I doing logging or debugging?</p><pre>Yes<br>↓<br>also</pre><p>Am I working with multiple properties of the same object?</p><pre>Yes<br>↓<br>with</pre><h3>Final Thoughts</h3><p>You don’t need to memorize Kotlin Scope Functions or their definitions.</p><p>Instead, ask yourself:</p><ul><li>What do I want to return?</li><li>Am I configuring an object or performing an extra operation?</li><li>Do I need null safety?</li><li>Am I working with the same object multiple times?</li></ul><p>Once you start thinking this way, choosing the right scope function becomes almost second nature.</p><p>The best way to learn them isn’t by memorizing theory — it’s by using them while building Android applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fb66514af1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Fast AI Chatbot in Android with OpenAI API and Jetpack Compose]]></title>
            <link>https://medium.com/@sagarjaulaniya13591/building-a-fast-ai-chatbot-in-android-with-openai-api-and-jetpack-compose-1e0f517dbb13?source=rss-fe105db1af1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e0f517dbb13</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[sagar jaulaniya]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 07:37:24 GMT</pubDate>
            <atom:updated>2026-06-24T07:37:24.349Z</atom:updated>
            <content:encoded><![CDATA[<p>AI-powered chatbots are becoming a common feature in Android applications. With OpenAI APIs and modern Android tools like Jetpack Compose, ViewModel, and Retrofit, you can build a chatbot in just a few steps.</p><p>This article covers a minimal production-ready implementation along with performance tips to make responses feel faster.</p><h4>Project Architecture</h4><pre>UI (Jetpack Compose)<br>        ↓<br>    ViewModel<br>        ↓<br>    Repository<br>        ↓<br>     Retrofit<br>        ↓<br>   OpenAI API</pre><p>This separation keeps the code clean, testable, and scalable.</p><ol><li>Add Dependencies</li></ol><pre>implementation(&quot;com.squareup.retrofit2:retrofit:2.11.0&quot;)<br>implementation(&quot;com.squareup.retrofit2:converter-gson:2.11.0&quot;)<br>implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.0&quot;)<br>implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2&quot;)</pre><p>2. API Models</p><pre>data class Message(<br>    val role: String,<br>    val content: String<br>)<br><br>data class ChatRequest(<br>    val model: String,<br>    val messages: List&lt;Message&gt;,<br>    val stream: Boolean = false<br>)<br><br>data class ChatResponse(<br>    val choices: List&lt;Choice&gt;<br>)<br><br>data class Choice(<br>    val message: Message<br>)</pre><p>3. Retrofit Service</p><pre>interface OpenAiApi {<br><br>    @POST(&quot;v1/chat/completions&quot;)<br>    suspend fun chat(<br>        @Header(&quot;Authorization&quot;) token: String,<br>        @Body request: ChatRequest<br>    ): ChatResponse<br>}</pre><pre>object RetrofitClient {<br><br>    private const val BASE_URL =<br>        &quot;https://api.openai.com/&quot;<br><br>    val api: OpenAiApi by lazy {<br>        Retrofit.Builder()<br>            .baseUrl(BASE_URL)<br>            .addConverterFactory(<br>                GsonConverterFactory.create()<br>            )<br>            .build()<br>            .create(OpenAiApi::class.java)<br>    }<br>}</pre><p>4. Repository</p><pre>class ChatRepository {<br><br>    suspend fun sendMessage(<br>        prompt: String<br>    ): String {<br><br>        val request = ChatRequest(<br>            model = &quot;gpt-4o-mini&quot;,<br>            messages = listOf(<br>                Message(<br>                    role = &quot;user&quot;,<br>                    content = prompt<br>                )<br>            )<br>        )<br><br>        return RetrofitClient.api.chat(<br>            token = &quot;Bearer API_KEY&quot;,<br>            request = request<br>        ).choices.first().message.content<br>    }<br>}</pre><p>5. ViewModel</p><pre>class ChatViewModel(<br>    private val repository: ChatRepository<br>) : ViewModel() {<br><br>    private val _response = MutableStateFlow(&quot;&quot;)<br><br>    val response = _response.asStateFlow()<br><br>    fun askQuestion(prompt: String) {<br><br>        viewModelScope.launch {<br><br>            runCatching {<br>                repository.sendMessage(prompt)<br>            }.onSuccess {<br>                _response.value = it<br>            }.onFailure {<br>                _response.value =<br>                    &quot;Something went wrong&quot;<br>            }<br>        }<br>    }<br>}</pre><blockquote><strong><em>6. Jetpack Compose UI</em></strong></blockquote><pre>@Composable<br>fun ChatScreen(<br>    viewModel: ChatViewModel<br>) {<br><br>    var prompt by remember {mutableStateOf(&quot;&quot;)}<br><br>    val response by viewModel.response.collectAsState()<br><br>    Column(<br>        modifier = Modifier.padding(16.dp)<br>    ) {<br><br>        OutlinedTextField(<br>            value = prompt,<br>            onValueChange = {<br>                prompt = it<br>            },<br>            label = {<br>                Text(&quot;Ask anything&quot;)<br>            }<br>        )<br><br>        Spacer(<br>            modifier = Modifier.height(12.dp)<br>        )<br><br>        Button(<br>            onClick = {<br>                viewModel.askQuestion(prompt)<br>            }<br>        ) {<br>            Text(&quot;Send&quot;)<br>        }<br><br>        Spacer(<br>            modifier = Modifier.height(16.dp)<br>        )<br><br>        Text(response)<br>    }<br>}</pre><h3>Making Responses Faster 🚀</h3><h4>Enable Streaming</h4><p>Instead of waiting for the complete response:</p><pre>{<br> &quot;stream&quot;: true<br>}</pre><p>Users start seeing tokens immediately, creating the familiar ChatGPT typing effect.</p><h4>Use Smaller Models</h4><p>For chatbot apps:</p><pre>GPT-4o Mini<br>Gemini Flash<br>Claude Haiku</pre><p>These models are typically faster and cheaper than larger reasoning models.</p><h4>Send Less Context</h4><p>Avoid sending the entire chat history.</p><pre>❌ 100 messages<br>✅ Last 10-20 relevant messages</pre><p>Smaller requests result in lower latency.</p><h4>Show Typing State</h4><pre>isLoading = true</pre><p>Display:</p><pre>AI is typing...</pre><p>This improves perceived performance even before the first token arrives.</p><h4>Security Best Practice</h4><p>Never store API keys in your Android application.</p><pre>const val API_KEY = &quot;...&quot;</pre><p>Instead:</p><pre>Android App<br>      ↓<br>Backend<br>      ↓<br>OpenAI API</pre><p>Keeping keys on the server protects your application from abuse and unexpected costs.</p><h4>Final Thoughts</h4><p>Building an AI chatbot in Android is straightforward with Retrofit, Coroutines, ViewModel, and Jetpack Compose. For the best user experience, focus not only on AI quality but also on speed. Streaming responses, limiting context size, and choosing the right model can make your chatbot feel significantly more responsive while reducing API costs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e0f517dbb13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Navigation 3 in Android: A Modern Approach to Jetpack Compose Navigation]]></title>
            <link>https://medium.com/@sagarjaulaniya13591/navigation-3-in-android-a-modern-approach-to-jetpack-compose-navigation-7ab049e1b461?source=rss-fe105db1af1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab049e1b461</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-navigation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[sagar jaulaniya]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 14:14:24 GMT</pubDate>
            <atom:updated>2026-04-08T14:14:24.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Navigation 3 in Android: The New Era of Jetpack Compose Navigation</h3><blockquote><em>A modern, state-driven approach to navigation that replaces fragments, XML graphs, and complex back stacks.</em></blockquote><h3>📌 Introduction</h3><p>Android navigation has gone through a major transformation. With the rise of <strong>Jetpack Compose</strong>, traditional navigation methods using fragments and XML are becoming less relevant.</p><p>Enter <strong>Navigation 3</strong> — a <strong>declarative, state-driven navigation approach</strong> that aligns perfectly with modern Android architecture.</p><p>If you’re building scalable and maintainable apps today, this is something you should not ignore.</p><h3>🔍 What is Navigation 3?</h3><p>Navigation 3 is a <strong>conceptual shift</strong> rather than just a new library.</p><p>Instead of:</p><ul><li>Calling navigation functions (like navigate())</li><li>Managing fragments</li><li>Handling XML navigation graphs</li></ul><p>👉 You simply <strong>change state</strong>, and UI updates automatically.</p><h3>🧭 Traditional vs Modern Navigation</h3><h3>🟥 Old Way (Navigation Component)</h3><ul><li>Fragment-based</li><li>XML navigation graphs</li><li>NavController driven</li><li>Harder to test</li></ul><h3>🟩 New Way (Navigation 3)</h3><ul><li>Composable screens</li><li>No XML</li><li>State-driven navigation</li><li>Easy to test &amp; debug</li></ul><p>🎨 Visual: How Navigation Changes</p><pre>OLD APPROACH (Imperative)<br>Button Click → navController.navigate(&quot;details&quot;) → UI Changes<br><br>NEW APPROACH (Declarative)<br>State Change → UI Recomposition → Screen Changes</pre><h3>🧠 Core Concept: Navigation = State</h3><p>At the heart of Navigation 3 is a simple idea:</p><blockquote><em>“Your screen is just a function of your state.”</em></blockquote><h3>✨ Example</h3><pre>sealed class Screen {<br>    data object Home : Screen()<br>    data class Details(val id: Int) : Screen()<br>}<br><br>@Composable<br>fun App() {<br>    var currentScreen by remember { mutableStateOf&lt;Screen&gt;(Screen.Home) }<br><br>    when (currentScreen) {<br>        is Screen.Home -&gt; HomeScreen(onClick = {<br>            currentScreen = Screen.Details(1)<br>        })<br>        is Screen.Details -&gt; DetailsScreen()<br>    }<br>}</pre><p>📌 No NavController. No routes. Just clean logic.</p><h3>🔐 Type-Safe Navigation (No More Strings)</h3><p>❌ Old Approach</p><pre>&quot;details/{id}&quot;</pre><p>✅ New Approach</p><pre>data class Details(val id: Int)</pre><h3>🎯 Why it matters:</h3><ul><li>Compile-time safety</li><li>No runtime crashes</li><li>Cleaner API</li></ul><h3>🔄 Visual: Back Stack Control</h3><pre>BackStack = [Home]<br><br>User navigates →<br>BackStack = [Home, Details]<br><br>User presses back →<br>BackStack = [Home]</pre><p>💻 Implementation</p><pre>val backStack = remember { mutableStateListOf&lt;Screen&gt;(Screen.Home) }<br><br>// Navigate<br>backStack.add(Screen.Details(2))<br><br>// Back<br>backStack.removeLast()</pre><p>👉 You are now in <strong>full control</strong>.</p><h3>🏗️ Scalable Architecture with ViewModel</h3><p>For real-world apps, move navigation to ViewModel:</p><pre>class NavViewModel : ViewModel() {<br>    var currentScreen by mutableStateOf&lt;Screen&gt;(Screen.Home)<br>}</pre><h3>📌 Benefits:</h3><ul><li>Survives configuration changes</li><li>Centralized logic</li><li>Better testability</li></ul><pre>| Feature    | Navigation Component | Navigation 3   |<br>| ---------- | -------------------- | -------------- |<br>| UI         | Fragments            | Compose        |<br>| Navigation | Imperative           | Declarative    |<br>| Routes     | Strings              | Type-safe      |<br>| Back Stack | Internal             | Manual control |<br>| XML        | Required             | Not needed     |</pre><h3>🎯 When Should You Use Navigation 3?</h3><p>✅ Use it if:</p><ul><li>You’re building with <strong>Jetpack Compose</strong></li><li>You want <strong>clean architecture</strong></li><li>You prefer <strong>state-driven UI</strong></li><li>You’re exploring <strong>Kotlin Multiplatform</strong></li></ul><p>❌ Avoid if:</p><ul><li>Your app is fully fragment-based</li><li>You rely heavily on legacy navigation</li></ul><h3>📈 Why It’s the Future</h3><p>Navigation 3 aligns with modern principles:</p><ul><li><strong>Unidirectional Data Flow (UDF)</strong></li><li><strong>Single Source of Truth (SSOT)</strong></li><li><strong>Composable UI</strong></li></ul><p>It removes unnecessary complexity and gives developers <strong>predictable behavior</strong>.</p><h3>🧩 Final Thoughts</h3><p>Navigation 3 is not just a better way to navigate — it’s a better way to <strong>think about app architecture</strong>.</p><p>By treating navigation as <strong>state</strong>, you:</p><ul><li>Reduce bugs</li><li>Improve readability</li><li>Gain full control over your app flow</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab049e1b461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Unnecessary Recompositions in Jetpack Compose (Performance Guide)]]></title>
            <link>https://medium.com/@sagarjaulaniya13591/avoiding-unnecessary-recompositions-in-jetpack-compose-performance-guide-6c36949d78c7?source=rss-fe105db1af1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c36949d78c7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[sagar jaulaniya]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 16:32:33 GMT</pubDate>
            <atom:updated>2026-03-12T16:32:33.979Z</atom:updated>
            <content:encoded><![CDATA[<p>When building UI with <strong>Jetpack Compose</strong>, one of the most important concepts to understand is <strong>recomposition</strong>.</p><p>Recomposition happens whenever the state used by a composable changes. Compose then <strong>re-executes the composable function to update the UI</strong>.</p><p>This is powerful, but if recomposition happens <strong>too frequently or unnecessarily</strong>, it can lead to <strong>performance issues and UI lag</strong>.</p><p>In this article, we’ll look at simple techniques to <strong>avoid unnecessary recompositions</strong> and keep your UI efficient.</p><h3>What is Recomposition?</h3><p>Recomposition is the process where Compose <strong>re-runs a composable function</strong> when its state changes.</p><p>Example:</p><pre>@Composable<br>fun Counter() {<br>    var count by remember { mutableStateOf(0) }<br><br>    Button(onClick = { count++ }) {<br>        Text(&quot;Count: $count&quot;)<br>    }<br>}</pre><p>When count changes, Compose recomposes the UI to update the text.</p><p>Recomposition itself is <strong>not bad</strong>. The problem occurs when <strong>too many composables recompose unnecessarily</strong>.</p><h3>1. Use remember to Avoid Recreating Objects</h3><p>If you create objects inside a composable without remember, they are recreated during every recomposition.</p><p>Bad example:</p><pre>val formatter = SimpleDateFormat(&quot;HH:mm&quot;)</pre><p>This object will be recreated on every recomposition.</p><p>Better approach:</p><pre>val formatter = remember { SimpleDateFormat(&quot;HH:mm&quot;) }</pre><p>Now the object is <strong>created only once</strong> and reused across recompositions.</p><h3>2. Use derivedStateOf for Computed State</h3><p>Sometimes UI depends on <strong>derived values</strong> calculated from other state.</p><p>Instead of recalculating every time, use derivedStateOf.</p><p>Example:</p><pre>val isButtonEnabled by remember {<br>    derivedStateOf { items.size &gt; 5 }<br>}</pre><p>Now the value is recalculated <strong>only when </strong><strong>items changes</strong>, not during every recomposition.</p><p>This helps reduce unnecessary work.</p><h3>3. Avoid Passing Unstable Objects</h3><p>If you pass new objects to composables on every recomposition, Compose may <strong>recompose child components unnecessarily</strong>.</p><p>Example:</p><pre>UserCard(user = User(name = &quot;John&quot;))</pre><p>Here, a new User object is created each time.</p><p>Better approach:</p><pre>val user = remember { User(&quot;John&quot;) }<br>UserCard(user = user)</pre><p>This keeps the object <strong>stable</strong> across recompositions.</p><h3>4. Use Keys in Lazy Lists</h3><p>In lists like LazyColumn, Compose needs to know <strong>which item changed</strong>.</p><p>Bad example:</p><pre>LazyColumn {<br>    items(users) {<br>        UserRow(it)<br>    }<br>}</pre><p>Better approach:</p><pre>LazyColumn {<br>    items(users, key = { it.id }) {<br>        UserRow(it)<br>    }<br>}</pre><p>Keys help Compose <strong>avoid recomposing unchanged items</strong>.</p><h3>5. Keep State as Close as Possible to Where It’s Used</h3><p>If state is placed too high in the UI hierarchy, it can trigger <strong>large parts of the UI to recompose</strong>.</p><p>Example problem:</p><pre>Screen<br> ├── Header<br> ├── Content<br> └── Footer</pre><p>If the state is stored in Screen, changing it might recompose <strong>all children</strong>.</p><p>Better approach:<br>Move state closer to the composable that actually uses it.</p><p>This limits recomposition to <strong>smaller UI areas</strong>.</p><h3>Quick Summary</h3><ul><li>Use <strong>remember</strong> to cache objects.</li><li>Use <strong>derivedStateOf</strong> for computed values.</li><li>Avoid passing <strong>new objects during recomposition</strong>.</li><li>Use <strong>keys in LazyColumn</strong> lists.</li><li>Keep <strong>state close to where it’s used</strong>.</li></ul><h3>Final Thoughts</h3><p>Recomposition is a core feature of Jetpack Compose and makes UI updates simple and reactive.</p><p>However, understanding how to <strong>control recomposition</strong> is essential for building <strong>smooth and performant apps</strong>.</p><p>By applying these small optimizations, you can significantly <strong>reduce unnecessary recompositions and improve UI performance</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c36949d78c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Side Effects: LaunchedEffect,  SideEffect, DisposableEffect  (Beginner Guide)]]></title>
            <link>https://medium.com/@sagarjaulaniya13591/jetpack-compose-side-effects-launchedeffect-sideeffect-disposableeffect-beginner-guide-eb7cbfa26657?source=rss-fe105db1af1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb7cbfa26657</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[sagar jaulaniya]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 04:26:01 GMT</pubDate>
            <atom:updated>2026-07-19T08:59:29.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jetpack Compose Side Effects (Beginner Guide)</h3><p>When I first started learning Jetpack Compose, one thing that confused me was all the different Side Effect APIs. Most of them sound similar, so it’s hard to know which one to use and when.</p><p>The easiest way to understand them is to ask yourself one question:</p><blockquote><strong><em>“When should this piece of code run?”</em></strong></blockquote><p>Composable functions should only describe the UI. If you want to make an API call, launch a coroutine, observe lifecycle changes, or perform any operation outside UI rendering, you’ll need a Side Effect API.</p><p>Let’s look at them one by one.</p><h4>1. LaunchedEffect</h4><p>Use it when something should happen automatically when the composable enters the composition.</p><pre>@Composable<br>fun UserScreen(userId: String) {<br><br>    LaunchedEffect(userId) {<br>        viewModel.loadUser(userId)<br>    }<br>}</pre><h4>What happens?</h4><ul><li>Runs when the screen is displayed.</li><li>Runs again if userId changes.</li><li>Cancels the coroutine when the composable leaves the screen.</li></ul><h4>Common use cases</h4><ul><li>API calls</li><li>Collecting Flows</li><li>Loading initial data</li></ul><blockquote><em>If it should happen automatically when the screen opens, use </em><em>LaunchedEffect.</em></blockquote><h4>2. rememberCoroutineScope</h4><p>Use it when you want to launch a coroutine based on a user action.</p><pre>@Composable<br>fun ExampleScreen() {<br><br>    val scope = rememberCoroutineScope()<br><br>    Button(<br>        onClick = {<br>            scope.launch {<br>                delay(1000)<br>                println(&quot;Button clicked&quot;)<br>            }<br>        }<br>    ) {<br>        Text(&quot;Click Me&quot;)<br>    }<br>}</pre><h4>Common use cases</h4><ul><li>Button clicks</li><li>Showing Snackbars</li><li>User-triggered actions</li></ul><blockquote><em>If the user clicks something, </em><em>rememberCoroutineScope is usually the right choice.</em></blockquote><h4>3. SideEffect</h4><p>Runs after every successful recomposition.</p><pre>@Composable<br>fun ProfileScreen(userName: String) {<br><br>    SideEffect {<br>        analytics.setUserName(userName)<br>    }<br><br>    Text(text = userName)<br>}</pre><h4>Common use cases</h4><ul><li>Analytics events</li><li>Updating external SDKs</li><li>Passing Compose state to non-Compose code</li></ul><blockquote><em>Use it when you need to synchronize Compose state with something outside Compose.</em></blockquote><h4>4. DisposableEffect</h4><p>Used when setup and cleanup logic are required.</p><pre>@Composable<br>fun ObserveLifecycle(lifecycle: Lifecycle) {<br><br>    DisposableEffect(lifecycle) {<br><br>        val observer =<br>            LifecycleEventObserver { _, event -&gt;<br>                println(&quot;Lifecycle Event : $event&quot;)<br>            }<br><br>        lifecycle.addObserver(observer)<br><br>        onDispose {<br>            lifecycle.removeObserver(observer)<br>        }<br>    }<br>}</pre><h4>Common use cases</h4><ul><li>Lifecycle observers</li><li>Broadcast receivers</li><li>Sensor listeners</li></ul><blockquote><em>Need setup and cleanup? Use </em><em>DisposableEffect.</em></blockquote><h4>5. rememberUpdatedState</h4><p>Provides the latest value inside long-running side effects without restarting them.</p><pre>@Composable<br>fun SplashScreen(onTimeout: () -&gt; Unit) {<br><br>    val latestOnTimeout by rememberUpdatedState(onTimeout)<br><br>    LaunchedEffect(Unit) {<br>        delay(3000)<br>        latestOnTimeout()<br>    }<br>}</pre><h4>Common use cases</h4><ul><li>Splash screens</li><li>Timers</li><li>Delayed navigation</li></ul><blockquote><em>Useful when a callback or value can change while a coroutine is still running.</em></blockquote><h4>6. produceState</h4><p>Converts asynchronous data into Compose State.</p><pre>@Composable<br>fun loadUser(userId: String): State&lt;User?&gt; {<br><br>    return produceState(<br>        initialValue = null,<br>        userId<br>    ) {<br>        value = repository.getUser(userId)<br>    }<br>}</pre><p>Usage:</p><pre>val user by loadUser(userId)</pre><h4>Common use cases</h4><ul><li>API responses</li><li>Repository data</li><li>External callbacks</li></ul><blockquote><em>Think of it as “Coroutine + State = produceState”.</em></blockquote><h4>7. derivedStateOf</h4><p>Used for calculated values that shouldn’t trigger unnecessary recompositions.</p><pre>val listState = rememberLazyListState()<br><br>val showScrollButton by remember {<br>    derivedStateOf {<br>        listState.firstVisibleItemIndex &gt; 0<br>    }<br>}</pre><h4>Common use cases</h4><ul><li>Scroll-based UI changes</li><li>Performance optimizations</li><li>Expensive calculations</li></ul><blockquote><em>Use it when one state depends on another state.</em></blockquote><h4>8. snapshotFlow</h4><p>Converts Compose State into Kotlin Flow.</p><pre>LaunchedEffect(listState) {<br><br>    snapshotFlow {<br>        listState.firstVisibleItemIndex<br>    }.collect { index -&gt;<br>        println(&quot;Current Index: $index&quot;)<br>    }<br>}</pre><h4>Common use cases</h4><ul><li>Scroll tracking</li><li>Analytics</li><li>Search debouncing</li><li>Flow operators on Compose State</li></ul><blockquote><em>Use it when you want to observe Compose state using Kotlin Flow.</em></blockquote><h4>Quick Cheat Sheet</h4><pre>Side Effect API            | Use Case<br>----------------------------------------------------------<br>LaunchedEffect             | Run code when the screen opens<br>rememberCoroutineScope     | Run code on user actions<br>SideEffect                 | Run after recomposition<br>DisposableEffect           | Setup and cleanup logic<br>rememberUpdatedState       | Get the latest value in side effects<br>produceState               | Convert async data into State<br>derivedStateOf             | Optimize recompositions<br>snapshotFlow               | Convert State into Flow</pre><h4>Final Thoughts</h4><p>You don’t need to memorize every Side Effect API right away. In day-to-day Android development, you’ll mostly use LaunchedEffect, rememberCoroutineScope, and DisposableEffect.</p><p>Whenever you’re confused, just ask yourself:</p><blockquote><strong><em>“When should this code run?”</em></strong></blockquote><p>That one question will usually tell you which Side Effect API is the right fit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb7cbfa26657" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>