<?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 Nirali Pandya on Medium]]></title>
        <description><![CDATA[Stories by Nirali Pandya on Medium]]></description>
        <link>https://medium.com/@nehavaidya95?source=rss-b4eb0a0ed8da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bgmvm4QUYq5p6nB6fHA_jw.jpeg</url>
            <title>Stories by Nirali Pandya on Medium</title>
            <link>https://medium.com/@nehavaidya95?source=rss-b4eb0a0ed8da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:48:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nehavaidya95/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[Coroutine context and dispatchers in Kotlin]]></title>
            <link>https://medium.com/@nehavaidya95/coroutine-context-and-dispatchers-in-kotlin-f2cae7e75a8a?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2cae7e75a8a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine-context]]></category>
            <category><![CDATA[coroutine-dispatcher]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 00:14:31 GMT</pubDate>
            <atom:updated>2026-08-27T00:14:31.087Z</atom:updated>
            <content:encoded><![CDATA[<p>When we start working with Kotlin coroutines, two terms appear very often:</p><ul><li>Coroutine Context</li><li>Coroutine Dispatcher</li></ul><p>At first, they can seem confusing because both are related to how a coroutine runs. The easiest way to understand them is:</p><blockquote><strong><em>Coroutine context is a collection of information that controls how a coroutine behaves. A dispatcher is one part of that context that decides which thread or thread pool should execute the coroutine.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPWHtqU_DRdzpySW_oX6aQ.png" /><figcaption>Kotlin Context and Dispatchers</figcaption></figure><p>Let’s understand this step by step with Android examples.</p><h3>1. What is Coroutine Context?</h3><p>Every coroutine runs with a <strong>CoroutineContext</strong>.</p><p>A coroutine context is a collection of elements that provide information about the coroutine.</p><p>Some important elements are:</p><ul><li>Job — controls the coroutine&#39;s lifecycle</li><li>CoroutineDispatcher — decides where the coroutine runs</li><li>CoroutineName — gives the coroutine a name, useful for debugging</li><li>CoroutineExceptionHandler — handles uncaught coroutine exceptions</li></ul><p>For example:</p><pre>viewModelScope.launch {<br>    // Runs on Main by default<br><br>    launch {<br>        // Also inherits Main<br>    }<br><br>    launch(Dispatchers.IO) {<br>        // Uses IO instead<br>    }<br>}</pre><p>This coroutine does not start with an empty context.</p><p>It inherits the context from viewModelScope.</p><p>In this example, the outer coroutine is launched from viewModelScope, which uses the <strong>Main dispatcher by default</strong>. The first launch doesn&#39;t specify a dispatcher, so it <strong>inherits the context of its parent</strong> and also runs on Main. The second launch explicitly uses Dispatchers.IO, so it <strong>overrides the inherited dispatcher</strong> and runs on the IO dispatcher.</p><blockquote><strong><em>If you don’t specify a different context or dispatcher, a coroutine normally inherits the context of its parent.</em></strong></blockquote><p>This is why you don’t need to write Dispatchers.Main every time you launch a coroutine from an Android ViewModel.</p><h3>2. What is a Dispatcher?</h3><p>A dispatcher determines <strong>which thread or thread pool is used to execute a coroutine</strong>.</p><p>For example:</p><pre>launch(Dispatchers.IO) {<br>    // I/O work<br>}</pre><p>Here, Dispatchers.IO tells the coroutine to use the I/O dispatcher.</p><p>Kotlin provides several commonly used dispatchers:</p><ol><li>Dispatchers.Main</li><li>Dispatchers.IO</li><li>Dispatchers.Default</li><li>Dispatchers.Unconfined</li></ol><p>Let’s look at each one.</p><ol><li><strong>Dispatchers.Main:</strong></li></ol><p>Dispatchers.Main is used for work that needs to run on Android&#39;s main/UI<strong> </strong>thread.</p><p>For example:</p><pre>viewModelScope.launch(Dispatchers.Main) {<br>    // Update UI state<br>}</pre><h3>When should you use Main?</h3><p>Use it when the work needs to interact with UI-related components or main-thread-confined APIs.</p><p>For example:</p><pre>withContext(Dispatchers.Main) {<br>    // Update UI<br>}</pre><p><strong>2. Dispatchers.IO :</strong></p><p>Dispatchers.IO is designed for I/O operations.</p><p>I/O means operations where your program spends time waiting for something external.</p><p>Common examples include:</p><ul><li>Network requests</li><li>Reading files</li><li>Writing files</li><li>Database operations</li></ul><p>For example:</p><pre>viewModelScope.launch {<br>    val data = withContext(Dispatchers.IO) {<br>        repository.fetchData()<br>    }<br>}</pre><p>The important part is:</p><pre>withContext(Dispatchers.IO)</pre><p>It moves that block of work to the IO dispatcher.</p><h3>Example</h3><p>Imagine we are loading data from a database:</p><pre>val users = withContext(Dispatchers.IO) {<br>    userDao.getUsers()<br>}</pre><p>The database operation runs using the IO dispatcher.</p><p>After withContext finishes, execution resumes in the original coroutine context.</p><p><strong>3. Dispatchers.Default :</strong></p><p>Dispatchers.Default is designed for CPU-intensive work.</p><p>CPU-intensive work means the application needs to spend CPU power calculating something.</p><p>Examples include:</p><ul><li>Sorting a large list</li><li>Processing a large amount of data</li><li>Complex calculations</li><li>Parsing or transforming large data sets</li></ul><p>For example:</p><pre>val result = withContext(Dispatchers.Default) {<br>    calculateSomething()<br>}</pre><p>A simple way to remember the difference:</p><blockquote><strong><em>IO = waiting for external work</em></strong></blockquote><blockquote><strong><em>Default = doing CPU-heavy work</em></strong></blockquote><p>For example:</p><pre>withContext(Dispatchers.IO) {<br>    api.fetchData()<br>}</pre><p>The application is mostly waiting for the network.</p><p>But:</p><pre>withContext(Dispatchers.Default) {<br>    processLargeDataSet()<br>}</pre><p>The CPU is doing the actual computation.</p><p>4. Dispatchers.Unconfined :</p><p>Dispatchers.Unconfined is different from the other dispatchers.</p><p>It doesn’t confine the coroutine to a specific thread.</p><p>For example:</p><pre>launch(Dispatchers.Unconfined) {<br>    // Coroutine starts in the current call-frame<br>}</pre><p>After a suspension point, it can resume on a different thread depending on the suspending function.</p><p>Because of this behavior, Dispatchers.Unconfined is not something you normally choose for everyday Android development.</p><h3>Conclusion</h3><p>Coroutine Context and Dispatchers become much easier once we separate their responsibilities.</p><p><strong>CoroutineContext</strong> is a collection of information that defines how a coroutine behaves.</p><p><strong>CoroutineDispatcher</strong> is one element of that context and determines where coroutine execution is dispatched.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2cae7e75a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CollectAsState vs collectAsStateWithLifecycle in Jetpack Compose]]></title>
            <link>https://medium.com/@nehavaidya95/collectasstate-vs-collectasstatewithlifecycle-in-jetpack-compose-868732c92c11?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/868732c92c11</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-stateflow]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 03:10:42 GMT</pubDate>
            <atom:updated>2026-03-04T19:21:57.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>collectAsState vs collectAsStateWithLifecycle in Jetpack Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sq66-ImN3f0PQp6nN_howQ.png" /></figure><p>When building Android apps with Jetpack Compose, you often work with Flow or StateFlow inside a ViewModel. These flows emit data over time, and your UI needs to react to those updates automatically.</p><p>To collect a Flow inside a composable, Compose gives us two main functions: collectAsState() and collectAsStateWithLifecycle().</p><p>They look similar. They even behave similarly in many cases. But there is one important difference that can affect performance and resource usage in real apps.</p><p>Let’s understand both in a simple way.</p><p><strong>Understanding collectAsState()</strong></p><p>collectAsState() is the original API used to collect a Flow inside a composable.</p><p>It converts the values emitted by a Flow into Compose State. Whenever the flow emits a new value, the composable recomposes and updates the UI.</p><p>Here is a simple example.</p><pre>class MyViewModel : ViewModel() {<br>    private val _counter = MutableStateFlow(0)<br>    val counter: StateFlow&lt;Int&gt; = _counter<br><br>    fun increment() {<br>        _counter.value++<br>    }<br>}<br><br>@Composable<br>fun CounterScreen(viewModel: MyViewModel) {<br>    val count = viewModel.counter.collectAsState()<br><br>    Column {<br>        Text(text = &quot;Count: ${count.value}&quot;)<br>        Button(onClick = { viewModel.increment() }) {<br>            Text(&quot;Increase&quot;)<br>        }<br>    }<br>}</pre><p>Every time increment() is called, the StateFlow emits a new value. Because we used collectAsState(), the composable automatically recomposes and shows the updated count.</p><p>This works perfectly.</p><p>But there is something important happening behind the scenes.</p><p>collectAsState() will keep collecting the flow as long as the composable exists in memory. It does not automatically stop when the screen goes into the background or when the user navigates away.</p><p>In small apps, this may not cause problems. In larger apps, it can.</p><h3>A Real Scenario Where It Matters</h3><p>Imagine you have a screen that observes live stock prices from a Flow that updates every second.</p><pre>@Composable<br>fun StockScreen(viewModel: StockViewModel) {<br>    val price = viewModel.stockPrice.collectAsState()<br><br>    Text(text = &quot;Price: ${price.value}&quot;)<br>}</pre><p>Now suppose the user navigates to another screen. Even though this screen is not visible anymore, collectAsState() may continue collecting the stock price updates if the composable is still in the composition.</p><p>That means background work continues even when the user cannot see the UI.</p><p>If you have multiple screens like this, it can increase CPU usage and battery consumption.</p><p>This is why lifecycle awareness becomes important.</p><h4><strong>Enter collectAsStateWithLifecycle()</strong></h4><p>collectAsStateWithLifecycle() was introduced to solve this problem.</p><p>It behaves almost exactly like collectAsState(), but with one major improvement. It only collects the Flow when the composable’s lifecycle is at least in the STARTED state.</p><p>In simple words, it collects data only when the screen is visible and active.</p><p>Here is the same example rewritten.</p><pre>@Composable<br>fun StockScreen(viewModel: StockViewModel) {<br>    val price = viewModel.stockPrice.collectAsStateWithLifecycle()<br><br>    Text(text = &quot;Price: ${price.value}&quot;)<br>}</pre><p>Now when the user navigates away from this screen, the Flow collection automatically stops. When the user comes back, it resumes again.</p><p>You do not need to manually handle lifecycle changes. It works automatically.</p><h3>Example with Navigation</h3><p>Let’s say you are using Navigation Compose and you have two screens.</p><p>The first screen shows a list of users coming from a Flow.</p><pre>@Composable<br>fun UserListScreen(viewModel: UserViewModel) {<br>    val users = viewModel.users.collectAsStateWithLifecycle()<br><br>    LazyColumn {<br>        items(users.value) { user -&gt;<br>            Text(text = user.name)<br>        }<br>    }<br>}</pre><p>When the user navigates to a details screen, this list screen moves to the background.</p><p>If you used collectAsState(), the list might continue observing updates even though it is not visible.</p><p>If you use collectAsStateWithLifecycle(), the collection pauses automatically. When the user presses back and returns, it resumes.</p><p>This makes the behavior more efficient without changing your overall structure.</p><blockquote>The main idea is simple:</blockquote><p>Scrolling is not the problem.<br>Background lifecycle state is the real difference.</p><h3>So Which One Should You Use?</h3><p>If you are building a simple app or a quick demo project, collectAsState() works fine. It is simple and direct.</p><p>But in real production apps with multiple screens, navigation, background states, and heavy data updates, collectAsStateWithLifecycle() is usually the better choice.</p><p>It gives you automatic lifecycle handling.<br> It prevents unnecessary background work.<br> It keeps your UI reactive.<br> It improves efficiency without extra effort.</p><p>In modern Android development, especially when working with ViewModels and Flow, collectAsStateWithLifecycle() should generally be your default choice.</p><h3>Final Thoughts</h3><p>Both functions convert Flow into Compose State and trigger recomposition when data changes.</p><p>The difference is not about how they update the UI. The difference is about when they collect data.</p><p>collectAsState() collects as long as the composable exists.</p><p>collectAsStateWithLifecycle() collects only when the screen is active and visible.</p><p>Understanding this small difference helps you write more efficient and scalable Compose applications.</p><p>When building real-world apps, lifecycle awareness is not optional. It is essential.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=868732c92c11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dagger in Android: Simplifying Dependency Injection]]></title>
            <link>https://medium.com/@nehavaidya95/understanding-dagger-in-android-simplifying-dependency-injection-0011d440e1b1?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/0011d440e1b1</guid>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 20:41:39 GMT</pubDate>
            <atom:updated>2025-07-09T19:38:28.896Z</atom:updated>
            <content:encoded><![CDATA[<p>Dagger is dependancy framework ,a library which helps us managing the dependancies easily.</p><p>In Android development, managing dependencies manually can become a repetitive and error-prone task. Every time we need access to a helper class like NetworkHelper or DatabaseHelper, we end up writing similar boilerplate code to instantiate and pass them around. This not only clutters our codebase but also makes testing more difficult. That’s where <strong>Dagger</strong>, a powerful Dependency Injection (DI) framework, comes in.</p><pre>val networkHelper = NetworkHelper(context)<br>val databaseHelper = DatabaseHelper(context)</pre><p>This leads to:</p><p>Boilerplate code across the app. Tight coupling, making it hard to test or replace dependencies.Difficulty in managing object scopes, like ensuring only one instance of a helper exists (Singleton)</p><h3>What is Dagger?</h3><p><strong>Dagger</strong> is a compile-time dependency injection framework developed by Google. It helps you manage dependencies using <strong>annotations</strong>, and generates code behind the scenes to handle object creation and scoping.</p><p>Think of Dagger as a <strong>shopkeeper</strong>. If you want to buy a “ladies purse” (a specific object), you just need to tell the shopkeeper what you want. Similarly, you just annotate your classes, and Dagger will know how to provide them.</p><p>Understanding Dagger: The Shopkeeper Analogy</p><p>Imagine going to a shop to buy a ladies purse. Do you go to the warehouse and assemble it yourself? Of course not. You simply go to the shopkeeper and say:</p><p>Imagine walking into a store and saying to the shopkeeper:</p><blockquote><em>“I need a purse.”</em></blockquote><p>You don’t need to explain what a purse is, where it’s kept, how it should be wrapped, or whether it’s a reusable item. The shopkeeper already knows all that. You simply state your need, and the shopkeeper takes care of the rest .Fetching the right item and handing it over, perfectly wrapped and ready to go.</p><p>Now, let’s shift this scenario into the world of Android development using <strong>Dagger</strong>, the popular dependency injection framework.</p><p>In this analogy:</p><ul><li><strong>You</strong> are the Android app</li><li>The <strong>shopkeeper</strong> is the <strong>Dagger compiler</strong></li><li>The <strong>purse</strong> is the <strong>dependency</strong> you need (say, DatabaseHelper)</li><li>And your <strong>instruction</strong> is given through <strong>annotations</strong></li></ul><p>When you tell Dagger, “I need DatabaseHelper,&quot; you’re not concerned with how it’s constructed or where its dependencies come from. You just annotate your request, and Dagger takes care of the rest behind the scenes—resolving the dependency graph, understanding scopes, and delivering the right object exactly when and where it’s needed.</p><p>This is the beauty of Dagger: it abstracts away the tedious manual work of creating and managing dependencies. Just like a good shopkeeper, it already knows what you want and how to get it done — quickly, correctly, and efficiently.</p><p>And Dagger’s compiler goes to work behind the scenes — assembling the object, managing its lifecycle, and giving it to you fully wrapped.</p><p>You don’t need to worry about how it’s built — Dagger handles the complexity for you.</p><p><strong>Giving Signals to Dagger (Compiler)</strong></p><p>So how does the shopkeeper (compiler) know what to prepare?</p><p>Simple — you give signals. These signals come in the form of annotations like @Inject, @Singleton, or @Provides.</p><p>When the Dagger compiler sees these annotations, it understands:</p><p>“Ah! This class is needed. And the app wants it to be a singleton. Let me create the required object graph.”</p><p>In this analogy:<br>- You don’t give the shopkeeper all the details<br>- You just tell him what you need<br>- And Dagger figures out how to create it, when to reuse it, and where to inject it.</p><p>During build time:<br>- The compiler looks at all your annotations<br>- Generates new classes behind the scenes<br>- Sets up object graphs, singleton scopes, and dependency trees</p><p>After building, if you look into your build/generated/ folder, you’ll find classes like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*gLPxVEWddSwrhagoX-EMvw.png" /><figcaption>Generated Dagger class</figcaption></figure><p>So how actually dagger library and compiler works.Will understand with below example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0u8dNFdrG9fYIQvjU7EzUw.png" /><figcaption>Dagger-Internals</figcaption></figure><p>I have added custom two modules one for dagger library and one for dagger-compiler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*AbZRVSEUxwELHBA6sGzQrw.png" /></figure><p>If we look into dagger library there is only one class Component which defines annotation.This annotation doesn’t do anything by itself. It’s just a marker. In the real Dagger library, annotations like @Component, @Module, @Provides, etc., are all defined similarly.</p><p>So at this stage:</p><ul><li>We’ve only <strong>defined metadata</strong> (annotations).</li><li>No actual dependency logic is implemented.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5whJY3zU7oTHgndO9_ZGgA.png" /></figure><p>In the dagger-compiler module, we’ll simulate how the Dagger compiler works. In reality, Dagger uses <strong>annotation processors (APT or KAPT)</strong> to read these annotations and generate code.</p><p>We can mimic this using an annotation processor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*qGmkUw4pkX0_JxCusPK7Sg.png" /></figure><p>To tell the compiler about your custom processor, you create this file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Utvvk6hmXG-M4omRKgjNmw.png" /></figure><p>This is a standard Java SPI (Service Provider Interface) file. It ensures your processor is detected at compile time.</p><pre>package me.nirali.dagger.compiler<br><br>import com.squareup.kotlinpoet.*<br>import me.nirali.dagger.Component<br>import java.io.File<br>import javax.annotation.processing.*<br>import javax.lang.model.element.TypeElement<br><br>class Processor : AbstractProcessor() {<br><br>    override fun getSupportedAnnotationTypes(): MutableSet&lt;String&gt; {<br>        return mutableSetOf(Component::class.java.canonicalName)<br>    }<br><br>    override fun process(<br>        annotations: MutableSet&lt;out TypeElement&gt;?, roundEnv: RoundEnvironment<br>    ): Boolean {<br>        val kaptKotlinGeneratedDir = processingEnv.options[&quot;kapt.kotlin.generated&quot;] ?: return false<br><br>        roundEnv.getElementsAnnotatedWith(Component::class.java).forEach { element -&gt;<br>            val packageName = processingEnv.elementUtils.getPackageOf(element).toString()<br>            val interfaceName = element.simpleName.toString()<br>            val className = &quot;Dagger$interfaceName&quot;<br><br>            val typeSpec = TypeSpec.classBuilder(className)<br>                .addFunction(<br>                    FunSpec.builder(&quot;build&quot;)<br>                        .addStatement(&quot;println(%S)&quot;, &quot;$className created for $interfaceName&quot;)<br>                        .build()<br>                )<br>                .build()<br><br>            FileSpec.builder(packageName, className)<br>                .addType(typeSpec)<br>                .build()<br>                .writeTo(File(kaptKotlinGeneratedDir))<br>        }<br><br>        return true<br>    }<br>}</pre><p>In this class, the method getSupportedAnnotationTypes() tells the compiler which annotations we want to process — in this case, @Component. The process() method is where the actual logic resides. During compilation, it retrieves all classes annotated with @Component, extracts their names and package information, and uses <a href="https://square.github.io/kotlinpoet/">KotlinPoet</a> to generate a new class named with a Dagger prefix (e.g., DaggerMyComponent for a MyComponent interface).</p><p>For each of these generated classes, we also add a simple function called build(), which prints a message to indicate that the class was generated successfully. While this is a minimal example, it mimics the core behavior of Dagger’s internal processing — creating implementation classes based on annotated definitions.</p><p>In conclusion, annotation processing is a powerful tool that can automate boilerplate code and enable advanced patterns like compile-time dependency injection. With just a few lines of processor logic and KotlinPoet, we’ve recreated a basic form of what Dagger does under the hood. Understanding this process gives you a deeper appreciation for Dagger’s design — and opens doors for creating your own compile-time tools in Android development.</p><p>I appreciate you reading this piece. If you found this article helpful, please mark your appreciation by clicking the below. It makes a big difference to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0011d440e1b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When does the GC get Called in Android?]]></title>
            <link>https://medium.com/@nehavaidya95/when-does-the-gc-get-called-in-android-21a7aee3ffac?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a7aee3ffac</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 02:08:17 GMT</pubDate>
            <atom:updated>2025-07-05T14:37:22.657Z</atom:updated>
            <content:encoded><![CDATA[<p>In Android, <strong>GC</strong> stands for <strong>Garbage Collector</strong>, a component of the <strong>Java Virtual Machine (JVM)</strong> or <strong>ART (Android Runtime)</strong> that automatically reclaims memory by removing objects that are no longer in use.</p><p>Gc called in Android in some of the particular cases as below:</p><ol><li><strong>When we have memory Pressure : More Memory Needed</strong></li></ol><p>GC is triggered when the system is running low on memory and needs to allocate more for new objects.</p><p>For example:</p><pre>val mediaPlayer = MediaPlayer()<br>mediaPlayer.setDataSource(&quot;video_path&quot;)<br>mediaPlayer.prepare()  // May trigger GC if memory is tight</pre><p>Also , if other apps needs more memory then Gc gets called.</p><p><strong>2. Allocation Threshold Crossed: Many Objects Allocated</strong></p><p>If your app creates many short-lived objects rapidly (e.g., in loops or recursive calls), it may exceed a memory allocation threshold determined by the OS, prompting GC.</p><p>There are some threshold for object allocation and that will be decided on OS level if that crossed again GC will Run. Parsing a large JSON response where thousands of data objects are created.</p><pre>val jsonArray = JSONArray(largeJsonString)<br>for (i in 0 until jsonArray.length()) {<br>    val obj = jsonArray.getJSONObject(i)<br>    val item = DataModel(obj.getString(&quot;title&quot;))<br>    // GC may run after a threshold is reached<br>}</pre><p><strong>3. Explicit Gc called: System.gc()</strong></p><p>Developer manually suggests garbage collection. This should be used with caution. Clearing cached files and suggesting GC to free memory (e.g., after logout or memory cleanup screen).</p><pre>clearCacheFiles()<br>System.gc()  // Hint to GC, not guaranteed</pre><p><strong>4.Activity Lifecycle Events: Activity or Fragment Destroyed</strong></p><p>An activity is finished or fragment is removed, and references are cleared. After removing a fragment and its view is no longer reachable.</p><pre>startActivity(Intent(this, NextActivity::class.java))<br>finish()  // Old activity can now be collected by GCl</pre><p><strong>5. Background Gc: Run Gc in the background Periodically.</strong></p><p>Android may run GC in the background periodically to optimize memory usage, especially when the device is idle.</p><p>Quick Overview: Common Scenarios When GC Is Triggered in Android Apps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wN_A5soenZW_hxntLGGtIg.png" /></figure><h3>Final Tip</h3><p>Even though Android’s GC is automatic, developers must manage references properly and avoid memory leaks by:</p><ul><li>Releasing resources in onDestroy()</li><li>Avoiding static references to Context</li><li>Using tools like <strong>LeakCanary</strong> or <strong>Android Profiler.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a7aee3ffac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Flows in Kotlin :]]></title>
            <link>https://medium.com/@nehavaidya95/intro-to-flows-in-kotlin-c3261bb73d90?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3261bb73d90</guid>
            <category><![CDATA[suspend]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 18:53:23 GMT</pubDate>
            <atom:updated>2024-03-21T18:53:23.022Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to Flows in Kotlin :</h3><p>What is Flow?</p><p>A flow to fetch the latest updates from an API and modify them with flow operators.a Flow is a cold asynchronous stream of values.</p><p>In Kotlin Flow, operators and transformations are functions that allow you to modify, filter, combine, or process data within a flow.</p><p>In coroutines, a <em>flow</em> is a type that can emit multiple values sequentially, as opposed to <em>suspend functions</em> that return only a single value. For example, you can use a flow to receive live updates from a database.</p><p>There are three entities involved in streams of data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jm3wnFbTBvURFtLlcQAYRg.png" /><figcaption>Kotlin Flows <em>Entities</em></figcaption></figure><ul><li>A <strong>producer</strong> produces data that is added to the stream. Thanks to coroutines, flows can also produce data asynchronously.</li><li><strong>(Optional) Intermediaries</strong> can modify each value emitted into the stream or the stream itself.</li><li>A <strong>consumer</strong> consumes the values from the stream.</li><li>Let’s build the basic structure of using Kotlin Flows for asynchronous data streaming.</li></ul><pre>   private fun flows() {<br>//Producer<br>        val flow = flow&lt;Int&gt; {<br><br>            for (i in 0..5) {<br>                emit(i)<br>            }<br>        }<br><br>//Consumer<br>        val job = GlobalScope.launch {<br>            flow.collect()<br>            { num -&gt;<br>                delay(3000)<br>                println(&quot;The Current value is : $num&quot;)<br>            }<br>        }<br><br>        job.start()<br>    }</pre><p>Here, a flow is created using the flow builder function. This flow emits integer values (&lt;Int&gt;).</p><p>Within the flow { ... } block, we use a loop to emit integers from 0 to 5 using the emit function.</p><ul><li>We launch a new coroutine using GlobalScope.launch to collect and consume values from the flow.</li><li>The collect terminal operator is used to collect values emitted by the flow. It takes a lambda that processes each emitted value.</li><li>Inside the collect lambda, we delay for 3000 milliseconds (simulating some asynchronous operation for getting value noticable) and then print the current value being collected.</li><li>We start the coroutine job explicitly after it’s been launched to begin collecting values from the flow.</li></ul><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3261bb73d90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithms Made Easy With Kotlin]]></title>
            <link>https://medium.com/@nehavaidya95/sorting-algorithms-in-made-easy-with-kotlin-adb8bce3122e?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb8bce3122e</guid>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[space-complexity]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 12:19:28 GMT</pubDate>
            <atom:updated>2024-03-13T12:20:34.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-DGotPPN2-MqoG3nvZQlQ.jpeg" /><figcaption>Algorithms in kotlin</figcaption></figure><p>What is Algorithms?</p><p>In Computer Science, an algorithm is <strong>a list set of instructions, used to solve problems or perform tasks, based on the understanding</strong> of available alternatives.</p><p>Types of Algorithms:</p><p>There are many types of algorithms but the most important and fundamental algorithms are total Three.</p><ol><li>Sorting Algorithms</li><li>Searching Algorithms</li><li>Graph Algorithms</li></ol><p>Let’s discuss <strong>Sorting</strong> Algorithms in details:</p><p>Sorting Algorithms:</p><ul><li>A sorting algorithm is used to arrange elements of an array/list in a specific order.</li></ul><h3>Common Sorting Algorithms:</h3><ol><li>Selection Sort</li><li>Bubble Sort</li><li>Insertion Sort</li><li>Quick Sort</li><li>Merge Sort</li></ol><p>The efficiency of Algorithms can defined based on <strong>Time complexity</strong> and <strong>Space complexity</strong> of it.You wondering about what is it ?Let me Explain.</p><blockquote><strong>Time Complexity</strong>: Imagine you have a task to do, like sorting a bunch of numbers. Time complexity is like asking, “How long will it take for you to finish sorting if I give you more and more numbers?” If it takes twice as long when you double the numbers, it might have a “linear” time complexity. If it takes longer in a predictable way, like every time you add a number it takes a bit longer, it might have a “quadratic” time complexity. We use Big O notation to talk about this.</blockquote><blockquote><strong>Space Complexity</strong>: Now imagine you’re sorting those numbers, but you also need space to work with them. Space complexity is like asking, “How much space do you need to do the sorting?” If you need more space as you get more numbers, it might have a “linear” space complexity. If you need a lot more space every time you add just a few numbers, it might have a “quadratic” space complexity. Again, we use Big O notation for this.</blockquote><h3><strong>Selection Sort</strong></h3><pre>val list = arrayListOf(3, 4, 6, 8, 7, 0, 9, 10)<br>            printCount(list)<br>            for (i in list) Log.d(&quot;ArrayList&quot;, &quot;List elements: $list&quot;)<br><br><br>private fun printCount(list: ArrayList&lt;Int&gt;): ArrayList&lt;Int&gt; {<br>        var smallest: Int<br>        for (i in 0 until list.size) {<br>            smallest = i<br>            for (j in (i + 1) until list.size) {<br>                if (list[smallest] &gt; list[j]) {<br>                    smallest = j<br>                }<br><br>            }<br>            swap(list, smallest, i)<br>            Log.e(&quot;TAG&quot;, &quot;printCount: $smallest&gt;&gt;$i&quot;)<br>        }<br>        return list<br>    }<br><br>    <br>private fun swap(a: ArrayList&lt;Int&gt;, b: Int, c: Int) {<br>        val temp = a[b]<br>        a[b] = a[c]<br>        a[c] = temp<br>    }</pre><p>Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and moving it to the beginning. Here’s a simplified explanation of how it works:</p><p>1.Find the smallest element in the unsorted array.<br>2.Swap it with the element at the beginning of the unsorted array.<br>3.Repeat this process for the remaining unsorted elements.</p><p>As you can see, in the above example, it consists of two for loops in above example. The <strong>time complexity</strong> of selection sort is<strong> O(n²)</strong>, where ’n’ is the number of elements in the array. This means that the time it takes to sort the array grows quadratically with the number of elements.</p><p>The <strong>space complexity</strong> of selection sort is<strong> O(1)</strong>, which means it uses constant space. Regardless of the size of the input array, selection sort only requires a fixed amount of additional space for storing temporary variables or indices used in the sorting process.</p><p>Total no. of passes: (n-1)</p><p>Total no. of comparisons: n*(n-1)/2</p><h3>Bubble Sort</h3><pre> private fun bubbleShort(array: ArrayList&lt;Int&gt;) {<br>        for (i in 0 until array.size) {<br>            for (j in 0 until array.size-1) {<br>                if (array[j] &gt; array[j+1])<br>                {<br>                    val temp = array[j]<br>                    array[j]= array[j+1]<br>                    array[j+1] =temp<br>                }<br>            }<br>        }<br><br>    }</pre><p>Bubble sort is another simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Here’s a simplified explanation of how it works:</p><p>1.Starting from the beginning of the list, compare the first two elements.<br>2.If the first element is greater than the second element, swap them.<br>3.Move to the next pair of adjacent elements and repeat the comparison and swapping process.<br>4.Continue this process until the end of the list is reached.<br>5.After the first pass, the largest element will be at the end of the list.<br>6.Repeat steps 1–5 for the remaining elements, excluding the last element from each subsequent pass as it is already in its correct position.</p><p>The <strong>time complexit</strong>y of bubble sort is also<strong> O(n²)</strong>, where ’n’ is the number of elements in the array. Similar to selection sort, this means that the time it takes to sort the array grows quadratically with the number of elements.</p><p>The <strong>space complexity</strong> of bubble sort is <strong>O(1)</strong>, indicating that it uses constant space. Regardless of the size of the input array, bubble sort only requires a fixed amount of additional space for storing temporary variables or indices used in the sorting process.</p><p>Total number of passes: (n-1)<br>Total number of comparisons: n*(n-1)/2</p><h3>Insertion Sort</h3><pre>private fun insertionSort(array: IntArray) {<br>    var n = array.size<br>    for (i in 1 until n) {<br>        var key = array[i]<br>        var j = i - 1<br>        Log.d(TAG, &quot;insertionSort: $key&gt;&gt;$j&quot;)<br><br>        /* Move elements of arr[0..i-1], that are<br>           greater than key, to one position ahead<br>           of their current position */<br>    <br>        while (j &gt;= 0 &amp;&amp; array[j] &gt; key) {<br>            array[j + 1] = array[j]<br>            j -= 1<br>            Log.d(TAG, &quot;insertionSort: $j&quot;)<br><br>        }<br>        array[j + 1] = key<br><br>    }<br>}</pre><p>Insertion sort is another simple sorting algorithm that works by repeatedly taking one element from the unsorted part of the list and inserting it into its correct position within the sorted part of the list. Here’s a simplified explanation of how it works:</p><ol><li>Starting from the second element (index 1) of the list, compare it with the elements to its left.</li><li>2.If the element to the left is greater than the current element, shift the element to the left one position to make space for the current element.</li><li>3.Continue this process until you find the correct position for the current element in the sorted part of the list.</li><li>4.Repeat steps 1–3 for each element in the list, gradually expanding the sorted portion of the list until all elements are in their correct positions.</li></ol><p>The time complexity of insertion sort is O(n2), where n is the number of elements in the array. This is because, in the worst-case scenario, each element needs to be compared and possibly shifted to its correct position within the sorted portion of the list.</p><p>The space complexity of insertion sort is O(1), indicating that it uses constant space. Similar to bubble sort, regardless of the size of the input array, insertion sort only requires a fixed amount of additional space for storing temporary variables or indices used in the sorting process.</p><p>Total number of passes: n−1<br>Total number of comparisons: n×(n−1)/2</p><h3>Characteristics of Insertion Sort</h3><ul><li>This algorithm is one of the simplest algorithms with a simple implementation</li><li>Basically, Insertion sort is efficient for small data values</li><li>Insertion sort is adaptive in nature, i.e. it is appropriate for data sets that are already partially sorted.</li></ul><h3>Quick Sort</h3><pre>private fun quickSort(array: ArrayList&lt;Int&gt;, low: Int, high: Int) {<br>    if (high &lt;= low) return<br>    var pivot: Int = partition(array, low, high)<br>    quickSort(array, low, pivot - 1)<br>    quickSort(array, pivot + 1, high)<br><br>}<br><br>private fun partition(array: ArrayList&lt;Int&gt;, low: Int, high: Int): Int {<br>    var pivot = array[high]<br>    var i = low - 1<br>    for (j in low until high ) {<br>        if (array[j] &lt; pivot) {<br>            i++<br>            var temp = array[i]<br>            array[i] = array[j]<br>            array[j] = temp<br>        }<br>    }<br>    i++<br>    var temp = array[i]<br>    array[i] = pivot<br>    array[high] = temp<br><br>    return i<br>}</pre><p>We can call function like this:</p><pre>var array = arrayListOf&lt;Int&gt;(2, 3, 8, 7, 10, 5, 9)<br>            quickSort(array, 0, (array.size) - 1)</pre><p>QuickSort is a highly efficient, divide-and-conquer sorting algorithm that operates by partitioning an array into smaller subarrays and recursively sorting them. Here’s a simplified explanation of how QuickSort works:</p><p>1.Pivot Selection:</p><p>Choose a pivot element from the array. Common strategies include selecting the first, last, or middle element.</p><p>2.Partitioning:</p><p>Rearrange the elements in the array such that elements smaller than the pivot are on its left, and elements greater than the pivot are on its right.<br>The pivot is now in its final sorted position.</p><p>3.Recursion:</p><p>Apply QuickSort recursively to the subarrays on the left and right of the pivot.</p><p>4.Base Case:</p><p>The base case is when the subarray has one or zero elements, in which case it is already considered sorted.</p><p>The time complexity of QuickSort is typically O(n log n) on average, making it more efficient than insertion sort for large datasets. However, in the worst-case scenario, it can degrade to O(n²) when the pivot selection and partitioning lead to unbalanced subarrays. Randomized pivot selection helps mitigate this risk in practice.</p><p>The space complexity of QuickSort is O(log n) on average, representing the recursion stack’s maximum depth. This makes QuickSort use less space compared to many other sorting algorithms, contributing to its efficiency in terms of memory consumption.</p><p>In summary:</p><p>Total number of passes: log n (on average)<br>Total number of comparisons: O(n log n) on average, but O(n²) in the worst-case scenario</p><h3>Merge Sort</h3><pre>    private fun mergeSort(array: IntArray, start: Int, end: Int) {<br>        if (start &gt;= end) {<br>            return<br>        }<br>        var middle: Int = start + (end - start) / 2<br>        mergeSort(array, start, middle)<br>        mergeSort(array, middle + 1, end)<br>        conqure(array, start, middle, end)<br>    }<br><br>    private fun conqure(array: IntArray, start: Int, middle: Int, end: Int) {<br>        var merger = IntArray(end - start + 1)<br>        var idx1 = start;<br>        var idx2 = middle + 1;<br>        var x = 0<br>        while (idx1 &lt;= middle &amp;&amp; idx2 &lt;= end) {<br>            if (array[idx1] &lt;= array[idx2]) {<br>                merger[x++] = array[idx1++];<br>            } else {<br>                merger[x++] = array[idx2++]<br>            }<br>        }<br><br>        while (idx1 &lt;= middle) {<br>            merger[x++] = array[idx1++];<br><br>        }<br>        while (idx2 &lt;= end) {<br>            merger[x++] = array[idx2++];<br>        }<br><br>        var j = start<br><br>        for (i in merger.indices) {<br>            // Access merger[i] and merger[j] in the loop<br>            array[start + i] = merger[i]<br>        }<br><br>        println(&quot;Sorted Array : ${Arrays.toString(merger)}&quot;)<br>    } </pre><p>Merge Sort is a robust, recursive sorting algorithm that follows the divide-and-conquer approach to efficiently sort an array. Here’s a simplified breakdown of how Merge Sort operates:</p><p>Divide:</p><ul><li>Split the array into two halves.</li><li>Recursively divide each half until each subarray contains one element.</li></ul><p>Conquer (Merge):</p><ul><li>Merge the divided subarrays back together in a sorted manner.</li><li>Compare elements from each subarray and place them in the correct order.</li></ul><ol><li>Base Case:</li></ol><ul><li>The base case is when the subarray has one or zero elements, which is inherently sorted.</li></ul><p>Merge Sort guarantees a time complexity of O(n log n) in all scenarios, making it more predictable than QuickSort. This efficiency comes from its consistent splitting and merging process, ensuring balanced subarrays throughout. Additionally, its space complexity is O(n) due to the need for auxiliary arrays during merging.</p><p>In summary:</p><ul><li>Total number of passes: log n</li><li>Total number of comparisons: O(n log n)</li></ul><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb8bce3122e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to RxJava and RxAndroid]]></title>
            <link>https://medium.com/@nehavaidya95/introduction-to-rxjava-and-rxandroid-72c42cc90ff9?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c42cc90ff9</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[rxko]]></category>
            <category><![CDATA[observer]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 21:11:47 GMT</pubDate>
            <atom:updated>2024-02-02T21:11:47.432Z</atom:updated>
            <content:encoded><![CDATA[<p>RxJava is a Java library for composing asynchronous and event-based programs using observable sequences. It implements the principles of reactive programming, providing developers with tools to handle asynchronous tasks, such as network requests or UI events, in a more declarative and composable way.</p><p>RxAndroid, on the other hand, is an extension of RxJava tailored specifically for Android development. It provides additional functionality and support to seamlessly integrate reactive programming into Android applications. RxAndroid offers features like scheduling tasks on the Android main thread, lifecycle awareness, and integration with Android components like Views and Activities, making it easier for developers to write reactive and responsive code for Android apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eXana22RutUqmFhJiClT3w.png" /></figure><p>Dependancy for both:</p><pre>implementation &#39;io.reactivex.rxjava3:rxandroid:3.0.2&#39;<br>// Because RxAndroid releases are few and far between, it is recommended you also<br>// explicitly depend on RxJava&#39;s latest version for bug fixes and new features.<br>// (see https://github.com/ReactiveX/RxJava/releases for latest 3.x.x version)<br>implementation &#39;io.reactivex.rxjava3:rxjava:3.1.5&#39;</pre><p><strong>Observables and Observers</strong></p><p>Observable: Think of it as a stream of data or events that can be observed over time. It emits items or events and can emit zero or more items.</p><p>Observer: It subscribes to an Observable to receive notifications about new items or events emitted by the Observable. It reacts to these emissions by defining callback methods such as onNext(), onError(), and onComplete().</p><p>In summary, Observables emit data, and Observers react to that data. They form the core components of the Observer design pattern, central to reactive programming.</p><p>Let’s achieve this in Kotlin:</p><pre>data class Task(<br>    val description: String? = null,<br>     val isComplete: Boolean? = false,<br>     val priority: Int? = 0<br>)</pre><pre>open class DataSource {<br><br> fun createTask() : List&lt;Task&gt; {<br>        var tasks = arrayListOf&lt;Task&gt;()<br>        tasks.add(Task(&quot;I want to learn Algorithms&quot;,false,3))<br>        tasks.add(Task(&quot;I want to learn RxJava&quot;,true,5))<br>        tasks.add(Task(&quot;I want to learn Python&quot;,false,1))<br>        tasks.add(Task(&quot;I want to learn DataStructure&quot;,false,2))<br>        return tasks<br>    }<br>}</pre><pre>val tasks: Observable&lt;Task&gt; = Observable.fromIterable(DataSource().createTask())<br>    .subscribeOn(Schedulers.io())<br>    .filter { task -&gt;<br>        println(&quot;Filter: ${Thread.currentThread().name}&quot;)<br>        Thread.sleep(1000)<br>        task.isComplete == true<br>    }<br>    .observeOn(AndroidSchedulers.mainThread())<br>tasks.subscribe(<br>    { task -&gt;<br>        // onNext - Action to perform for each emitted task<br>        // For example, log the task description<br>        println(&quot;Task Description: ${Thread.currentThread().name}&quot;)<br>        println(&quot;Task Description: ${task.description}&quot;)<br>    },<br>    { error -&gt;<br>        // onError - Action to perform if an error occurs<br>        // For example, log the error message<br>        println(&quot;An error occurred: $error&quot;)<br>    },<br>    { // onComplete - Action to perform when all tasks are emitted<br>        // For example, show a completion message<br>        println(&quot;All tasks emitted&quot;)<br>    }<br>)</pre><p><strong>Observable.fromIterable</strong>: This method creates an Observable that emits each item in an Iterable or Collection. In this context, it’s used to create an Observable from a list of tasks obtained from DataSource().createTask().</p><p><strong>subscribeOn</strong>: This operator specifies the Scheduler (thread) on which the source Observable will operate. In this case, subscribeOn(Schedulers.io()) indicates that the Observable’s operations, such as emitting items from the list of tasks, will occur on the I/O thread pool, typically used for blocking I/O operations.</p><p><strong>filter</strong>: This operator filters the items emitted by the source Observable based on a specified condition. In this code, .filter { task -&gt; task.isComplete == true } ensures that only tasks marked as complete are allowed to pass through to the next stage of the Observable chain.</p><p><strong>observeOn</strong>: This operator specifies the Scheduler (thread) on which the Observer (subscription) will operate. In this code, .observeOn(AndroidSchedulers.mainThread()) ensures that the Observer’s callbacks, such as onNext(), onError(), and onComplete(), will run on the main thread, typically used for UI-related operations in Android apps.</p><p>Key <strong>benefits</strong> of using RxAndroid:</p><ol><li>Concise and readable code: Enables writing asynchronous code more cleanly and succinctly.</li><li>Threading abstraction: Simplifies threading management and avoids common concurrency issues.</li><li>Integration with Android components: Seamlessly integrates with Android UI components for reactive UI updates.</li><li>Lifecycle awareness: Automatically manages subscriptions based on Android component lifecycles, preventing memory leaks.</li><li>Error handling: Provides streamlined error handling within reactive streams.</li><li>Composition and transformation: Offers a wide range of operators for composing and transforming data streams.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c42cc90ff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inline functions]]></title>
            <link>https://medium.com/@nehavaidya95/inline-functions-3032cc1ca531?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/3032cc1ca531</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[inline-functions]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 19:18:35 GMT</pubDate>
            <atom:updated>2024-01-15T19:18:35.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Inline functions let the compiler copy and paste the entire function code wherever it’s used, which can make the program run faster by avoiding the need for separate function calls.</p><p>Inline functions not only avoid the overhead of function calls by inserting the code directly but can also eliminate the need for creating and initializing objects separately, streamlining the code for improved efficiency.</p><p>Let’s begin with basic example,</p><p>Simple function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOknxJpmx-Zf5UPVf-2azw.png" /><figcaption>Simple Function calling</figcaption></figure><p>Let’s look at the <strong>bytecode</strong> of function,you can notice New keyword used ,that means new object creation taking place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*agf791TomkvnMXr7zi0jzg.png" /></figure><p>When inserting inline keyword to function printCount then check byteCode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCVCTVGPo9hF7HKczq9D-w.png" /></figure><p>We can see that it just simply pasted line of code of function, no object creation.</p><p>Let’s see one more example to illustrate this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77-DyaR-S1HhJmkM72C6eQ.png" /></figure><p>In this example,<strong> the Sub </strong>function is marked <strong>as inline</strong>. It takes two integers, n and m, and a lambda expression representing an operation to be performed on n and m. When <strong>Sub</strong> is called, instead of generating a function call, the compiler directly replaces the code inside the function with the code from the lambda expression.</p><p>So, in the main function, the call to Sub(10, 4) will be replaced with the actual code 10–4. <strong>This eliminates the overhead of creating an anonymous class and improves performance</strong>.</p><p>Follow for more…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3032cc1ca531" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dagger-Hilt Dependancy Injection]]></title>
            <link>https://medium.com/@nehavaidya95/dagger-hilt-dependancy-injection-abcdd8158bab?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/abcdd8158bab</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[injection]]></category>
            <category><![CDATA[dependancy-injection]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 21:55:37 GMT</pubDate>
            <atom:updated>2024-01-13T23:10:15.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Hilt?</h3><p>Hilt Dependancy injection frees you from writing tedious and error-prone boilerplate code.</p><p>Hilt is a powerful and intuitive dependency injection library designed specifically for Android app development. Developed by Google, Hilt is built on top of Dagger, a well-established and widely-used dependency injection (DI) library. The primary goal of Hilt is to streamline and simplify the process of dependency injection in Android applications, reducing boilerplate code and enhancing developer productivity.</p><h3>Basic Concepts:</h3><ol><li>@HiltAndroidApp: To enable Hilt in an Android application, developers typically annotate their Application class with @HiltAndroidApp. This annotation triggers the generation of the necessary Dagger components.</li><li>@AndroidEntryPoint: To enable dependency injection in Android components, such as activities and fragments, developers use the @AndroidEntryPoint annotation. This annotation informs Hilt to inject the required dependencies into the annotated Android component.</li><li>@Inject and @ViewModelInject: Hilt uses the @Inject annotation to mark the constructor of a class that requires dependency injection. For ViewModels, Hilt provides @ViewModelInject to simplify the injection process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91j5PfkJXzsnQFQ0Tlcj5w.png" /><figcaption>Hilt-Flow</figcaption></figure><h4><strong>Step 1 : Add dependency in your build. gradle :</strong></h4><pre> //Dagger - Hilt<br>    implementation &quot;com.google.dagger:hilt-android:2.44&quot;<br>    kapt &quot;com.google.dagger:hilt-android-compiler:2.44&quot;<br>    kapt &quot;androidx.hilt:hilt-compiler:1.0.0&quot;</pre><h4>Step 2: Add plugin in Project Level build.gradle :</h4><pre>plugins {<br>    id &#39;com.android.application&#39; version &#39;8.1.0&#39; apply false<br>    id &#39;org.jetbrains.kotlin.android&#39; version &#39;1.8.0&#39; apply false<br>    id &#39;com.google.dagger.hilt.android&#39; version &#39;2.44&#39; apply false<br>}</pre><p>Now Start with adding Application Class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_uLHpB_5yNa4V2HOBN9kg.png" /></figure><p><strong>@HiltAndroidApp</strong><br> The application class in your Android project is marked with the <a href="http://twitter.com/HiltAndroidApp">@HiltAndroidApp</a> annotation. This explanation is vital for introducing the Handle part for your Android application. Hilt prepares the Dagger 2 modules and components required for dependency injection when you apply <a href="http://twitter.com/HiltAndroidApp">@HiltAndroidApp</a> to your Application class.</p><p>Now Create Hilt Modules :</p><p>A Hilt module is a class that is annotated with @Module. Like a <a href="https://developer.android.com/training/dependency-injection/dagger-android#dagger-modules">Dagger module</a>, it informs Hilt how to provide instances of certain types. Unlike Dagger modules, you must annotate Hilt modules with @InstallIn to tell Hilt which Android class each module will be used or installed in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KikZCFIiJUdNPcDJHUfxOg.png" /><figcaption>AppModule.kt</figcaption></figure><p>Let me breakdown the code:</p><p>@Module: This annotation is used to mark the class as a Dagger Hilt module. Modules are used to group related bindings (provided dependencies) together.</p><p>@InstallIn(SingletonComponent::class): This annotation specifies the Hilt component where the bindings in the module should be installed. In your case, it&#39;s the SingletonComponent, which means the dependencies will have a singleton scope.</p><p>object AppModule: This declares an object named AppModule, which contains the Dagger Hilt module.</p><p>@Provides: This annotation is used to annotate methods inside a Dagger Hilt module, indicating that the annotated method provides a dependency.</p><p>@Singleton: This annotation specifies that the provided dependency should have a singleton scope, meaning that only one instance of the provided dependency will be created and reused throughout the application.</p><p>fun provideApplicationContext(application: Application): Context: This method provides the application context as a dependency. It takes an Application instance as a parameter and returns the application context.</p><p>Create Activity class :</p><pre>package com.example.daggerdependancyinjectiondemo.ui<br><br>import android.content.Context<br>import android.content.Intent<br>import android.net.Uri<br>import android.os.Bundle<br>import android.util.Log<br>import android.view.LayoutInflater<br>import android.view.View<br>import android.widget.CheckBox<br>import android.widget.CompoundButton<br>import androidx.appcompat.widget.AppCompatButton<br>import androidx.core.content.ContextCompat<br>import com.example.daggerdependancyinjectiondemo.R<br>import com.example.daggerdependancyinjectiondemo.databinding.ActivityGetStartBinding<br>import com.example.daggerdependancyinjectiondemo.prefs.Prefs.Companion.PRIVACY_POLICY_LINK<br>import com.example.daggerdependancyinjectiondemo.service.UserService<br>import dagger.hilt.android.AndroidEntryPoint<br>import javax.inject.Inject<br><br>@AndroidEntryPoint<br>class GetStartActivity : BaseActivity&lt;ActivityGetStartBinding&gt;(),<br>    CompoundButton.OnCheckedChangeListener,<br>    View.OnClickListener {<br><br>    @Inject<br>    lateinit var userService: UserService<br>    private var btn_get_start: AppCompatButton? = null<br>    private var chkByClick: CheckBox? = null<br>    lateinit var txt_start_privacy: MessagesTextView<br>    private var isMain: Boolean = false<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        init()<br>        UIComponent()<br><br>    }<br><br>    override fun getViewBinding(inflator: LayoutInflater) =<br>        ActivityGetStartBinding.inflate(inflator)<br><br>    private fun init() {<br>        if (intent.extras != null) {<br>            isMain = intent.extras!!.getBoolean(&quot;isMain&quot;, false)<br>        }<br>    }<br><br>    private fun UIComponent() {<br><br><br>        chkByClick = binding.chkByClick<br>        chkByClick!!.setOnCheckedChangeListener(this)<br>        txt_start_privacy = binding.txtStartPrivacy<br>        // Access the injected dependency<br>        val user = userService.getUser()<br>        txt_start_privacy.text = user<br>        btn_get_start = binding.btnGetStart<br>        btn_get_start!!.setBackgroundResource(R.drawable.button_continue)<br>        btn_get_start!!.setTextColor(ContextCompat.getColor(this, R.color.color_grey_dark))<br>        txt_start_privacy!!.setOnClickListener(this)<br>        btn_get_start!!.setOnClickListener(this)<br><br>    }<br><br>    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {<br>        btn_get_start!!.setBackgroundResource(if (isChecked) R.drawable.button_continue else R.drawable.button_continue_grey)<br>        btn_get_start!!.setTextColor(<br>            ContextCompat.getColor(<br>                this,<br>                if (isChecked) R.color.white else R.color.black<br>            )<br>        )<br>    }<br><br>    override fun onClick(v: View?) {<br>        when (v!!.id) {<br>            R.id.btn_get_start -&gt;<br>                onClickStart()<br><br>            R.id.txt_start_privacy -&gt;<br>                openPrivacyPolicy(this)<br><br>        }<br>    }<br><br>    private fun openPrivacyPolicy(context: Context) {<br>        try {<br>            val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(PRIVACY_POLICY_LINK))<br>            context.startActivity(browserIntent)<br>        } catch (throwable: Throwable) {<br>            Log.i(<br>                &quot;Tag&quot;,<br>                &quot;openPrivacyPolicy: &quot; + throwable.message<br>            )<br>        }<br>    }<br><br>    private fun onClickStart() {<br>        startActivity(<br>            Intent(<br>                this@GetStartActivity,<br>                MainActivity::class.java<br>            ).putExtra(&quot;isMain&quot;, false)<br>        )<br><br>    }<br><br><br>}</pre><p>Once Hilt is set up in your Application class and an application-level component is available, Hilt can provide dependencies to other Android classes that have the @AndroidEntryPoint annotation: Here lateinit var txt_start_privacy: MessagesTextView is injected class .</p><p>MessageTextView.kt</p><pre>package com.example.daggerdependancyinjectiondemo.ui<br><br>import android.content.Context<br>import android.util.AttributeSet<br>import androidx.emoji2.widget.EmojiTextView<br>import com.example.daggerdependancyinjectiondemo.helpers.TextViewStyler<br>import dagger.hilt.android.AndroidEntryPoint<br>import javax.inject.Inject<br>@AndroidEntryPoint<br>open class MessagesTextView @JvmOverloads  constructor(<br>    context: Context, attrs: AttributeSet? = null,  defStyleAttr: Int = 0<br>) : EmojiTextView(context, attrs,defStyleAttr) {<br><br>    @Inject<br>    lateinit var textViewStyler: TextViewStyler<br>    var collapseEnabled: Boolean = false<br><br>    @Inject<br>    constructor(<br>        context: Context,<br>        attrs: AttributeSet? = null,<br>        defStyleAttr: Int = 0,<br>        defStyleRes: Int = 0<br>    ) : this(context, attrs, defStyleAttr) {<br>    }<br><br>    init {<br>        if (!isInEditMode) {<br>        } else {<br>            TextViewStyler.applyEditModeAttributes(this, attrs)<br>        }<br>    }<br><br>    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {<br>        super.onLayout(changed, left, top, right, bottom)<br><br>        if (collapseEnabled) {<br>            layout<br>                    ?.takeIf { layout -&gt; layout.lineCount &gt; 0 }<br>                    ?.let { layout -&gt; layout.getEllipsisCount(layout.lineCount - 1) }<br>                    ?.takeIf { ellipsisCount -&gt; ellipsisCount &gt; 0 }<br>                    ?.let { ellipsisCount -&gt; text.dropLast(ellipsisCount).lastIndexOf(&#39;,&#39;) }<br>                    ?.takeIf { lastComma -&gt; lastComma &gt;= 0 }<br>                    ?.let { lastComma -&gt;<br>                        val remainingNames = text.drop(lastComma).count { c -&gt; c == &#39;,&#39; }<br>                        text = &quot;${text.take(lastComma)}, +$remainingNames&quot;<br>                    }<br>        }<br>    }<br><br>    override fun setTextColor(color: Int) {<br>        super.setTextColor(color)<br>        setLinkTextColor(color)<br>    }<br><br>}</pre><p>Use below dependancy for //EmojiTextView<br>implementation “androidx.emoji2:emoji2-views:1.2.0-alpha04”</p><p>The purpose of this custom view seems to be to handle the styling and behavior of text messages in the UI. The class utilizes Dagger Hilt for dependency injection.</p><ul><li>MessagesTextView is declared as an open class (meaning it can be subclassed).</li><li>It extends EmojiTextView, an Android widget likely used for displaying text with emoji support.</li><li>The primary constructor takes three parameters: context (Context), attrs (AttributeSet), and defStyleAttr (Int).</li></ul><p><a href="http://twitter.com/Inject">@Inject</a><br>lateinit var textViewStyler: TextViewStyler</p><ul><li>The @Inject annotation is used to mark the textViewStyler property for dependency injection.</li><li>textViewStyler is a property of type TextViewStyler, and Dagger Hilt will provide its instance automatically.</li></ul><p>Secondary Constructor:</p><p>@Inject constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : this(context, attrs, defStyleAttr) {}</p><p>UserService.kt</p><pre>package com.example.daggerdependancyinjectiondemo.service<br><br>import javax.inject.Inject<br><br>class UserService @Inject constructor() {<br>    fun getUser(): String {<br>        return &quot;Simple Demo of Hilt-Dependency Injection..&quot;<br>    }<br>}</pre><p>activity_get_start.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;@color/white&quot;<br>  &gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/img_start_icon&quot;<br>        android:layout_width=&quot;150dp&quot;<br>        android:layout_height=&quot;150dp&quot;<br>        android:layout_marginBottom=&quot;15dp&quot;<br>        android:src=&quot;@mipmap/ic_launcher_round&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@id/txt_start_title_s&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot; /&gt;<br><br>    &lt;com.example.daggerdependancyinjectiondemo.ui.MessagesTextView<br>        android:id=&quot;@+id/txt_start_title_s&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;@string/app_name&quot;<br>        android:textColor=&quot;@color/textcolor1&quot;<br>        android:textSize=&quot;15sp&quot;<br>        android:textStyle=&quot;bold&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;CheckBox<br><br>        android:id=&quot;@+id/chkByClick&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;10sp&quot;<br>        android:layout_marginBottom=&quot;5sp&quot;<br>        android:backgroundTint=&quot;@color/bg&quot;<br>        android:gravity=&quot;start&quot;<br>        android:lineSpacingExtra=&quot;3sp&quot;<br>        android:paddingStart=&quot;3dp&quot;<br>        android:text=&quot;@string/by_taaping&quot;<br>        android:textColor=&quot;@color/textcolor2&quot;<br>        android:textSize=&quot;13sp&quot;<br>        android:visibility=&quot;gone&quot;<br>        android:button=&quot;@drawable/check&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@+id/btn_get_start&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot; /&gt;<br><br>    &lt;com.example.daggerdependancyinjectiondemo.ui.MessagesTextView<br>        android:id=&quot;@+id/txt_start_privacy&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginBottom=&quot;18dp&quot;<br>        android:text=&quot;@string/privacy_policy&quot;<br>        android:gravity=&quot;center&quot;<br>        android:padding=&quot;5dp&quot;<br>        android:textColor=&quot;@color/textcolor1&quot;<br>        android:textSize=&quot;10sp&quot;<br>        android:visibility=&quot;visible&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@id/btn_get_start&quot;<br>        app:layout_constraintStart_toStartOf=&quot;@id/chkByClick&quot;<br>        android:layout_marginStart=&quot;30sp&quot;/&gt;<br><br>    &lt;androidx.appcompat.widget.AppCompatButton<br>        android:id=&quot;@+id/btn_get_start&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_margin=&quot;50sp&quot;<br>        android:background=&quot;@drawable/button_continue&quot;<br>        android:text=&quot;@string/button_continue&quot;<br>        android:textColor=&quot;@color/white&quot;<br>        android:visibility=&quot;visible&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>For Further details go to repo here : <a href="https://github.com/Nirali123456789/DaggerDemo">https://github.com/Nirali123456789/DaggerDemo</a></p><p>Assuming you wish to investigate detail execution of Hilt Dependancy injection, kindly look at my GitHub store.</p><p>I appreciate you reading this piece. If you found this article helpful, please mark your appreciation by clicking the below. It makes a big difference to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abcdd8158bab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Android Development with Model-View-ViewModel (MVVM) With Retrofit: A Practical Example]]></title>
            <link>https://medium.com/@nehavaidya95/simplifying-android-development-with-model-view-viewmodel-mvvm-a-practical-example-6ea5d14c4bdc?source=rss-b4eb0a0ed8da------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea5d14c4bdc</guid>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[retrofit]]></category>
            <dc:creator><![CDATA[Nirali Pandya]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 21:00:23 GMT</pubDate>
            <atom:updated>2024-02-14T17:48:27.151Z</atom:updated>
            <content:encoded><![CDATA[<p>Model-View-ViewModel, or MVVM, is a design pattern that is frequently used in software development, particularly when it comes to user interfaces and apps. In frameworks like Android, WPF, and others where maintaining maintainability and separating concerns are essential, MVVM is particularly well-liked.</p><p><strong>When</strong> compared to other architectural <strong>patterns like</strong> Model-View-Controller (MVC) or Model-View-Presenter <strong>(MVP), the Model-View-ViewModel (MVVM) architecture has a number of advantages.</strong> Here are some of <strong>MVVM’s main benefits</strong> and how it differs from these other <strong>patterns:.</strong></p><p><strong>MVVM’s advantages include the following.</strong></p><p><strong>Separation</strong> of Concerns: MVVM <strong>requires</strong> a <strong>distinct division</strong> between the <strong>user interface (UI),</strong> business logic, and data.</p><p><strong>The</strong> codebase <strong>is</strong> easier <strong>to maintain, testing is simpler,</strong> and collaboration <strong>between various</strong> teams (designers, developers, testers, <strong>etc.) is made possible by this division.</strong></p><p><strong>Testability: MVVM’s</strong> separation of concerns <strong>enables</strong> more <strong>thorough</strong> and <strong>effective</strong> testing.</p><p><strong>It is simpler to write unit tests without involving the UI components because</strong> the ViewModel <strong>already contains the majority</strong> of the application logic and business <strong>rules.</strong></p><p><strong>Code</strong> Reusability: MVVM <strong>promotes</strong> the <strong>development</strong> of reusable components.</p><p>The same business logic and data manipulation <strong>can be reused</strong> across <strong>various</strong> UI <strong>implementations by designing the ViewModel to be independent of the UI.</strong></p><p>MVVM <strong>uses</strong> data binding to update the UI <strong>automatically</strong> when the underlying data <strong>changes, making UI updates simpler.</strong></p><p><strong>By doing so,</strong> the <strong>requirement</strong> for manual UI <strong>updates is removed,</strong> boilerplate code <strong>is cut down,</strong> and the <strong>likelihood of UI synchronization</strong> errors <strong>is reduced.</strong></p><p><strong>Flexibility</strong> for UI <strong>Modifications: Since</strong> the ViewModel <strong>serves</strong> as an intermediary, UI <strong>modifications</strong> can be made with <strong>little</strong> impact on the underlying logic.</p><p><strong>With regards to</strong> UI redesigns or <strong>adjustments</strong> to user <strong>interactions, this is especially helpful.</strong></p><p><strong>Improved</strong> Collaboration: <strong>As long as designers and developers abide by the established contract between the View and ViewModel, the</strong> separation between the design (View) and logic (ViewModel) layers in MVVM allows <strong>for</strong> more <strong>independent work.</strong></p><p><strong>Differences</strong> from Other <strong>Architectures:.</strong></p><p><strong>Model-View-Controller (MVC):</strong> In MVC, the Controller <strong>serves</strong> as an <strong>interface</strong> between the Model and <strong>the</strong> View, handling user input and updating the Model and View <strong>as necessary.</strong></p><p><strong>The</strong> need for direct <strong>communication</strong> between the View and <strong>Model is removed by MVVM,</strong> making the View passive and <strong>dependent</strong> on the ViewModel to handle user <strong>interactions and provide data.</strong></p><p><strong>Similar to the ViewModel in MVVM,</strong> the Presenter <strong>in MVP (Model-View-Presenter) acts</strong> as <strong>a bridge</strong> between the Model and the <strong>View.</strong></p><p><strong>Data binding, however, makes</strong> UI updates <strong>easier</strong> and <strong>eliminates</strong> the need for <strong>Presenter</strong> explicit <strong>updates.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA2EBb6QyGgizm0reHqbKg.png" /><figcaption>MVVM Architecture with Coroutines +Flow+Hilt</figcaption></figure><h3><strong>Dependencies to add in gradle file</strong></h3><pre>def navVersion = &quot;2.3.5&quot;<br> final def roomVersion = &quot;2.4.3&quot;<br>   kapt &quot;androidx.room:room-compiler:$roomVersion&quot;<br>    implementation &quot;androidx.room:room-ktx:$roomVersion&quot;<br>    implementation &quot;androidx.room:room-runtime:$roomVersion&quot;<br>//Mvvm Lifecycle<br>    implementation &quot;androidx.navigation:navigation-ui-ktx:2.5.3&quot;<br>    implementation &quot;androidx.navigation:navigation-fragment-ktx:2.5.3&quot;<br><br>//for dimens<br>    implementation &#39;com.intuit.sdp:sdp-android:1.1.0&#39;<br>    implementation &#39;com.github.bumptech.glide:glide:4.13.1&#39;<br><br><br>    // retrofit<br>    implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;<br>    implementation &#39;com.squareup.retrofit2:converter-gson:2.5.0&#39;</pre><p><strong>Code Demonstration:</strong></p><p>//BaseViewModel to use in All classes</p><pre>public abstract class BaseViewModel extends ViewModel {<br>}</pre><p>//ViewModel classs</p><pre>class CategoryViewModel(private val foodItemRepository: CategoryRepo) : ViewModel() {<br>    val allFoodItems: LiveData&lt;MutableList&lt;Jokes&gt;&gt; = foodItemRepository.alFoodItems<br><br>    class Factory(private val app: Application, private val repo: CategoryRepo) :<br>        ViewModelProvider.AndroidViewModelFactory(app) {<br>        override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T {<br>            return CategoryViewModel(repo) as T<br>        }<br><br>    }<br><br>    // Launching a new coroutine to insert the data in a non-blocking way<br>    fun insertAll(list: ArrayList&lt;Jokes&gt;) = viewModelScope.launch {<br>        foodItemRepository.alFoodItems.value = list<br>    }</pre><p><strong>Repository to bind with ViewModel:</strong></p><pre>class CategoryRepo(private val foodItemDao: CategoryDao, var page: Int = 1) {<br>  val alFoodItems: MutableLiveData&lt;MutableList&lt;Jokes&gt;&gt; = MutableLiveData()<br>}</pre><p><strong>DataModel class:</strong></p><pre>import androidx.room.Entity<br>import androidx.room.PrimaryKey<br><br>@Entity(tableName = &quot;Jokes&quot;)<br>class Jokes(<br>    @PrimaryKey<br>    var id: String = &quot;00&quot;, var error: String = &quot;&quot;, var amount: Int,<br>    var jokes: ArrayList&lt;Joke&gt;<br><br>)<br><br>class Joke {<br>    var setup: String = &quot;&quot;<br>    var delivery: String = &quot;&quot;<br>}</pre><p>MainActivity</p><pre>package com.example.myapplication.UI<br><br>import android.content.Context<br>import android.os.Build<br>import android.os.Bundle<br>import android.util.Log<br>import android.view.LayoutInflater<br>import android.widget.Toast<br>import androidx.activity.viewModels<br>import androidx.recyclerview.widget.DefaultItemAnimator<br>import androidx.recyclerview.widget.GridLayoutManager<br>import androidx.recyclerview.widget.LinearLayoutManager<br>import com.example.myapplication.Adapters.ThemeAdapter<br>import com.example.myapplication.App<br>import com.example.myapplication.Base.BaseActivity<br>import com.example.myapplication.Models.Joke<br>import com.example.myapplication.Models.Jokes<br>import com.example.myapplication.Retrofit.RetrofitClient<br>import com.example.myapplication.Viewmodels.CategoryViewModel<br>import com.example.myapplication.databinding.ActivityMainBinding<br>import retrofit2.Call<br>import retrofit2.Callback<br>import retrofit2.Response<br><br><br>class MainActivity : BaseActivity&lt;ActivityMainBinding, CategoryViewModel&gt;() {<br>    var list: ArrayList&lt;Jokes&gt; = arrayListOf()<br>    private var currentApiVersion = 0<br>    var arrlist: ArrayList&lt;Joke&gt; = arrayListOf()<br>    private lateinit var adapter: ThemeAdapter<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        currentApiVersion = Build.VERSION.SDK_INT<br>        super.onCreate(savedInstanceState)<br>        getJokes();<br><br><br>    }<br><br>    private fun getJokes() {<br>        val model: CategoryViewModel by viewModels() {<br>            CategoryViewModel.Factory(<br>                (application as App),<br>                (application as App).repository<br>            )<br>        }<br>        val call: Call&lt;Jokes&gt; = RetrofitClient.instance?.getMyApi()!!.getJokes(5,5)<br>        call.enqueue(object : Callback&lt;Jokes&gt; {<br>            override fun onResponse(<br>                call: Call&lt;Jokes&gt;,<br>                response: Response&lt;Jokes&gt;<br>            ) {<br>                Log.e(&quot;onResponse&quot;, &quot;onResponse: ${response.body()}&quot;)<br>                val jokesList: Jokes = (response.body())!!<br>                list.add(jokesList)<br>                model.insertAll(list)<br><br><br>            }<br><br>            override fun onFailure(call: Call&lt;Jokes&gt;, t: Throwable) {<br>                Toast.makeText(<br>                    applicationContext,<br>                    &quot;An error has occured${t.message}&quot;,<br>                    Toast.LENGTH_LONG<br>                ).show()<br>                Log.d(&quot;TAG&quot;, &quot;onFailure: ${t.message}&quot;)<br>            }<br>        })<br><br><br><br>        model.allFoodItems.observe(<br>            this<br>        ) {<br>            Log.d(&quot;getJokes&quot;, &quot;getJokes: ${it[0].jokes.size}&quot;)<br>            arrlist = it[0].jokes<br>            for (i in arrlist.indices)<br>            {<br>                Log.d(&quot;TAG&quot;, &quot;onBindViewHolder: ${arrlist.get(i)}&quot;)<br>            }<br>            adapter.setData(arrlist)<br>        }<br>        setupData()<br><br>    }<br><br>    private fun setupData() {<br>        adapter = ThemeAdapter(this)<br>        var layoutManager: LinearLayoutManager = LinearLayoutManager(this)<br>        binding.recyclerview.layoutManager =<br>            layoutManager<br>        binding.recyclerview.itemAnimator = DefaultItemAnimator()<br>        binding.recyclerview.adapter = adapter<br>    }<br><br><br>    override fun attachBaseContext(newBase: Context) {<br>        super.attachBaseContext(newBase)<br>    }<br><br><br>    override fun createViewBinding(layoutInflater: LayoutInflater?): ActivityMainBinding {<br>        return ActivityMainBinding.inflate(layoutInflater!!);<br>    }<br><br><br>}</pre><p>ThemeAdapter.kt</p><pre>package com.example.myapplication.Adapters<br><br>import android.app.Activity<br>import android.content.Context<br>import android.graphics.Bitmap<br>import android.util.Log<br>import android.view.LayoutInflater<br>import android.view.ViewGroup<br>import androidx.recyclerview.widget.DiffUtil<br>import androidx.recyclerview.widget.RecyclerView<br>import com.bumptech.glide.Glide<br>import com.bumptech.glide.load.DataSource<br>import com.bumptech.glide.load.engine.DiskCacheStrategy<br>import com.bumptech.glide.load.engine.GlideException<br>import com.bumptech.glide.request.RequestListener<br>import com.bumptech.glide.request.RequestOptions<br>import com.bumptech.glide.request.target.Target<br>import com.example.myapplication.Models.Joke<br>import com.example.myapplication.Models.Jokes<br>import com.example.myapplication.R<br>import com.example.myapplication.databinding.PosterItemsBinding<br>import java.util.Objects<br><br><br>class ThemeAdapter(var context: Activity) :<br>    RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() {<br>    var list: ArrayList&lt;Joke&gt; = arrayListOf()<br>    private val LOADING = 0<br>    private val ITEM = 1<br>    private var isLoadingAdded = false<br><br><br>    companion object ListItemCallback : DiffUtil.ItemCallback&lt;Jokes&gt;() {<br>        override fun areItemsTheSame(oldItem: Jokes, newItem: Jokes): Boolean {<br>            return oldItem == newItem<br>        }<br><br>        override fun areContentsTheSame(oldItem: Jokes, newItem: Jokes): Boolean {<br>            return oldItem.id == newItem.id<br>        }<br>    }<br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br><br>        val inflater = LayoutInflater.from(parent.context)<br>        val binding = PosterItemsBinding.inflate(inflater, parent, false)<br>        return PosterViewHolder(binding)<br>    }<br><br>    fun setData(posterList: ArrayList&lt;Joke&gt;) {<br><br>        list = posterList!!<br>        notifyDataSetChanged()<br>    }<br><br><br>    override fun onBindViewHolder(holder1: RecyclerView.ViewHolder, position: Int) {<br><br><br>        var holder: PosterViewHolder = holder1 as PosterViewHolder<br>        holder.setData(list.get(position), context)<br><br><br>    }<br><br>    override fun getItemCount(): Int {<br>        return list.size<br>    }<br><br>    class PosterViewHolder(val view: PosterItemsBinding) :<br>        RecyclerView.ViewHolder(view.root) {<br><br><br>        fun setData(<br>            poster: Joke,<br>            context: Context) {<br><br>            Log.d(&quot;TAG&quot;, &quot;setData: &quot; + &quot;onclick${poster.delivery}&quot;)<br>            view.setUp.text =poster.setup<br>            view.delievery.text =poster.delivery<br><br>        }<br>    }<br><br><br>}<br><br></pre><p>poster_items.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>    &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        android:id=&quot;@+id/li_1&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_margin=&quot;@dimen/_2sdp&quot;<br>        android:orientation=&quot;vertical&quot;&gt;<br><br>        &lt;RelativeLayout<br>            android:id=&quot;@+id/frame_1&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_margin=&quot;@dimen/_5sdp&quot;&gt;<br><br>            &lt;ImageView<br>                android:id=&quot;@+id/imgPoster&quot;<br>                android:layout_width=&quot;match_parent&quot;<br>                android:layout_height=&quot;match_parent&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:adjustViewBounds=&quot;true&quot;<br>                android:scaleType=&quot;fitXY&quot;<br>                android:src=&quot;@drawable/ic_placeholder&quot;<br>                android:visibility=&quot;gone&quot; /&gt;<br><br>            &lt;TextView<br>                android:visibility=&quot;visible&quot;<br>                android:id=&quot;@+id/setUp&quot;<br>                android:layout_width=&quot;match_parent&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:adjustViewBounds=&quot;true&quot;<br>                android:text=&quot;@string/app_name&quot;<br>                android:textColor=&quot;@color/black&quot;<br>                android:textSize=&quot;@dimen/_13sdp&quot; /&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/delievery&quot;<br>                android:layout_width=&quot;match_parent&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:textColor=&quot;@color/grey&quot;<br>                android:layout_below=&quot;@+id/setUp&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:layout_marginTop=&quot;@dimen/_2sdp&quot;<br>                android:text=&quot;@string/app_name&quot; /&gt;<br><br>        &lt;/RelativeLayout&gt;<br><br>    &lt;View<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;1px&quot;<br>        android:background=&quot;#B8B7B7&quot; /&gt;<br><br>    &lt;/LinearLayout&gt;</pre><p>Room Database Classes:</p><p>Database and Dao Classes:</p><pre>package com.example.myapplication.RoomDatabase<br><br>import android.content.Context<br>import androidx.room.*<br>import androidx.sqlite.db.SupportSQLiteDatabase<br>import com.example.myapplication.Models.Jokes<br>import com.example.myapplication.converters.Converters<br>import kotlinx.coroutines.CoroutineScope<br><br>@Database(entities = [Jokes::class], version = 1,exportSchema = false)<br>@TypeConverters(Converters::class)<br>abstract class CallDatabase : RoomDatabase() {<br><br>    abstract val categorydao: CategoryDao<br><br><br>    companion object {<br>        @Volatile<br>        public var INSTANCE: CallDatabase? = null<br><br>        fun getDatabase(context: Context, scope: CoroutineScope):CallDatabase{<br>            return INSTANCE ?: synchronized(this){<br>                val instance = Room.databaseBuilder(<br>                    context.applicationContext,<br>                    CallDatabase::class.java,<br>                    &quot;food_item_database&quot;<br>                ).addCallback(FoodItemCallback(scope))<br>                    .build()<br><br>                INSTANCE = instance<br><br>                // return instance<br>                instance<br>            }<br>        }<br>    }<br>    private class FoodItemCallback(val scope: CoroutineScope):RoomDatabase.Callback(){<br>        override fun onCreate(db: SupportSQLiteDatabase) {<br>            super.onCreate(db)<br><br><br>       }<br>    }<br>}</pre><pre>package com.example.myapplication.RoomDatabase<br><br>import androidx.room.Dao<br>import androidx.room.Insert<br>import androidx.room.OnConflictStrategy<br>import com.example.myapplication.Models.Jokes<br><br><br>@Dao<br>interface CategoryDao {<br><br><br><br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>     fun insertAll(Courses: ArrayList&lt;Jokes&gt;)<br><br>    @Insert(onConflict = OnConflictStrategy.IGNORE)<br>    suspend fun insert(foodItem: Jokes)<br>      <br>}</pre><p>Retrofit::</p><pre>package com.example.myapplication.Retrofit<br><br>import retrofit2.Retrofit<br>import retrofit2.converter.gson.GsonConverterFactory<br><br>class RetrofitClient private constructor() {<br>    val BASE_URL = &quot;https://v2.jokeapi.dev/joke/&quot;<br>    private val myApi: ApiInterface<br><br>    init {<br>        val retrofit: Retrofit = Retrofit.Builder().baseUrl(BASE_URL)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>        myApi = retrofit.create(ApiInterface::class.java)<br>    }<br><br>    fun getMyApi(): ApiInterface {<br>        return myApi<br>    }<br><br>    companion object {<br>        @get:Synchronized<br>        var instance: RetrofitClient? = null<br>            get() {<br>                if (field == null) {<br>                    field = RetrofitClient()<br>                }<br>                return field<br>            }<br>            private set<br>    }<br>}</pre><pre>package com.example.myapplication.Retrofit<br><br>import com.example.myapplication.Models.Jokes<br>import retrofit2.Call<br>import retrofit2.http.GET<br>import retrofit2.http.Path<br>import retrofit2.http.Query<br><br>interface ApiInterface {<br><br><br>    @GET(&quot;Christmas&quot;)<br>    fun getJokes(@Query(&quot;amount&quot;) amount: Int,@Query(&quot;twopart&quot;) twopart:Int): Call&lt;Jokes&gt;<br><br>}</pre><pre>package com.example.myapplication.converters<br><br>import androidx.room.TypeConverter<br>import com.example.myapplication.Models.Joke<br>import com.google.gson.Gson<br><br>class Converters {<br><br>    @TypeConverter<br>    fun listToJson(value: List&lt;Joke&gt;?) = Gson().toJson(value)<br><br>    @TypeConverter<br>    fun jsonToList(value: String) = Gson().fromJson(value, Array&lt;Joke&gt;::class.java).toList()<br>}</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*nPtVANNsac7ITixuA2qxTQ.png" /></figure><p>Happy coding……</p><p>Cheers🥂🥂…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea5d14c4bdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>