<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sagar N on Medium]]></title>
        <description><![CDATA[Stories by Sagar N on Medium]]></description>
        <link>https://medium.com/@nsagarrock?source=rss-7492b4f1c2b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wO90kFw6V0vd4-bnE_6Zdg.jpeg</url>
            <title>Stories by Sagar N on Medium</title>
            <link>https://medium.com/@nsagarrock?source=rss-7492b4f1c2b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:12:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nsagarrock/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[Fundamentals of Kotlin Coroutines Part 1]]></title>
            <link>https://nsagarrock.medium.com/fundamentals-of-kotlin-coroutines-part-1-ecb46f7a246d?source=rss-7492b4f1c2b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb46f7a246d</guid>
            <dc:creator><![CDATA[Sagar N]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 07:45:59 GMT</pubDate>
            <atom:updated>2025-06-22T09:09:44.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jI6KNJKzPOQRG0aEBh27_A.jpeg" /></figure><h4><strong>What are Coroutines in Kotlin?</strong></h4><p>They are high-level abstractions written on top of threads and help us express asynchronous code synchronously.</p><p>To understand this, first, we will have to know what the difference is between synchronous code and asynchronous code</p><h4>What is Synchronous and Asynchronous code?</h4><p>So let&#39;s understand <strong><em>synchronous code</em></strong>. It is pretty straightforward</p><p>The execution of the operation is in a linear path, meaning that one operation executes after the other operation completes, and in case the previous operation is long-running, then the next operation has to wait until the previous operation completes its execution</p><p>Example:</p><pre>fun main() {<br>    println(&quot;Weather forecast&quot;)<br>    println(&quot;Sunny&quot;)<br>}</pre><p>Output :</p><pre>Weather forecast<br>Sunny</pre><p>Now let&#39;s understand what <strong><em>asynchronous </em></strong>code<strong><em> </em></strong>is, the execution of multiple operations can happen concurrently, meaning that the execution of one operation does not need to wait for the next operation or the previous operation to complete</p><p>A better example for this would be the API service call, with the help of Retrofit.</p><pre>apiService.getUser(1).enqueue(object : Callback&lt;User&gt; {<br>    override fun onResponse(call: Call&lt;User&gt;, response: Response&lt;User&gt;) {<br>        if (response.isSuccessful) {<br>            val user = response.body()<br>            // Handle successful response<br>        } else {<br>            // Handle error<br>        }<br>    }<br><br>    override fun onFailure(call: Call&lt;User&gt;, t: Throwable) {<br>        // Handle failure<br>    }<br>}) </pre><p>From the above code, we are fetching user details (passing a callback to the enqueue function), which is a long-running network operation, but this block of code will not keep other subsequent operations waiting for it to complete. Once the response is fetched and it is successful, we get the user details.</p><p>Now let&#39;s see how we can express the same code in sequential style, meaning how asynchronous code looks like, with the help of <strong><em>kotlin</em></strong> <strong><em>Coroutines</em></strong>.</p><pre>lifecycleScope.launch {<br>    try {<br>        val user = apiService.getUser(1)<br>        // Use user<br>    } catch (e: Exception) {<br>        // Handle error<br>    }<br>}</pre><p>The above code uses the same API service call to request to get user details response, but here we have no callbacks. It works the same as previously, but it&#39;s more concise, simple, and readable than callbacks, handles errors with standard try/catch, and runs asynchronously</p><h3>Coroutines are lightweight</h3><p>Kotlin coroutines run on top of threads but are much more efficient and easier to manage.</p><p><strong><em>What does this mean?</em></strong></p><p>It means we can run more coroutines than threads. I am talking about native JVM threads, without exhausting the memory resource. We will understand this with the help of a program</p><p>Let&#39;s create 1000000 (1 million) coroutines</p><pre>fun coroutinesAreLightWeight() {<br>    val time = measureTime {<br>        runBlocking {<br>            repeat(1_000_000) { i -&gt; // launch a lot of coroutines<br>                launch {<br>                    println(&quot;Coroutine $i: .&quot;)<br>                }<br>            }<br>        }<br>    }<br><br>    println(&quot;Overall time that took for threads to finish -&gt; $time&quot;)<br><br>}</pre><p>In the above function, I am printing the index of the loop while launching a distinct coroutine using the <strong><em>launch</em></strong> coroutine builder ( will explain this on later articles)</p><p>Let’s see how much time it takes to run</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*Lkp-DLYzq_fdJ97NlMGWGg.png" /></figure><p>It took about 1.15 seconds.</p><p>Now let’s create around <strong>1 million</strong> <strong>native JVM threads</strong></p><pre>fun threadsAreHeavy() {<br>    val time = measureTime {<br>        repeat(1_000_000) { i -&gt;  // launch a lot of threads<br>           thread {<br>                println(&quot;Thread . $i&quot;)<br>            }<br>        }<br>    }<br><br>    println(&quot;Overall time that took for threads to finish -&gt; $time&quot;)<br>}</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*_o6ByDk0y_BD6q5CxyHhtg.png" /></figure><p>It took about 25 seconds to create 1 million threads.</p><p>From the above examples, we can observe that the coroutines are much lighter when compared to threads. Yes, they do have a small overhead, but they consume less memory when compared to threads. These numbers may vary depending on different operating systems, JDK versions, and settings. The creation of so many threads might exhaust the resources or start threads slowly so that there are not too many concurrently running threads, or throw an <strong>out-of-memory exception</strong> as well.</p><p>Let’s see all of the above functions that I have used</p><ul><li><strong>measureTime() </strong>executes a given block and returns the elapsed time</li><li><strong>runBlocking()</strong> This function acts like a bridge between regular code and code that can be written in a suspending style, and runs a coroutine and blocks the current thread until the whole block completes.</li><li><strong>repeat(1_000_000). </strong>This function runs a for loop inside, iterating from 0 to 1 million. In this case, it takes an int value as the parameter, which signifies the end range of the loop, and for each iteration, it runs the block passed, in the example program, I am launching a coroutine in the first example and on the second when creating a thread for each iteration, this function is pretty straight forward</li><li><strong>launch()</strong> This function is a coroutine builder; it launches a coroutine. This function can only work if it&#39;s inside a coroutine scope, the scope is provided by runBlocking {} in the example (will explain in more detail in a later article)</li><li><strong>thread() </strong>This function creates a thread and starts it immediately</li></ul><h4>Few Memory Leaks</h4><p>Yes, coroutines that are launched are delimited to their scope, and with the help of this, we can avoid memory leaks. A better example is the lifecycle scope, which is tagged with the lifecycle owner and follows the principle of <strong><em>structured concurrency</em></strong></p><p>To understand <strong><em>structured concurrency,</em></strong> let’s know <strong><em>what concurrency is.</em></strong></p><p>It means to execute multiple operations seemingly at the same time, and <strong><em>structured concurrency</em></strong> in kotlin coroutines is a relationship between the parent job and the child job. <strong><em>What is a Job? </em></strong>It&#39;s just a reference to the coroutine, when we launch a coroutine inside another coroutine, which is projected as a child coroutine, and the reference to it is the child job, when child coroutines are launched and if one produces an exception without handling it will propogate up to parent and the other will get canceled and the parent coroutine will be canceled at the end.</p><pre>lifecycleScope.launch {<br>    try {<br>        val user = apiService.getUser(1)<br>        // Use user<br>    } catch (e: Exception) {<br>        // Handle error<br>    }<br>}</pre><p>So, in the example above, when the <strong><em>lifecycleScope</em></strong> ends, the child coroutines get canceled. The child coroutine here is used in the method <strong><em>apiService.getUser(1), </em></strong>which is a suspend function ( will explain later what a suspend function does )</p><p>And <strong><em>what is lifecycleScope? </em></strong>This is a coroutineScope that is provided by the lifecycleOwner (Activity/Fragment). Any coroutine that is launched in this scope gets canceled when the <strong><em>lifecycle</em></strong> gets canceled, with the help of this, the resources that are held are cleaned up, avoiding any memory leaks</p><h4><strong>Built-in cancellation support</strong></h4><p>Cancellation in kotlin coroutines is cooperative, meaning if a coroutine is canceled, the suspending functions (from the package <strong>kotlinx.coroutines) </strong>support this cancellation by checking if the coroutine was canceled and throwing a <strong>CancellationException</strong>. The best example is <strong><em>delay()</em></strong>, which is a suspending function from the same package (<strong>kotlinx.coroutines)</strong></p><p>Let&#39;s try to understand from the example below</p><pre>fun withCooperation() = runBlocking {<br>    val job = launch {<br>        repeat(10) { i -&gt;<br>            println(&quot;job: I&#39;m sleeping $i ...&quot;)<br>            delay(500L)<br>        }<br>    }<br>    println(&quot;main: I&#39;m tired of waiting!&quot;)<br>    delay(2000) // delay a bit<br>    job.cancel() // cancels the job<br>    println(&quot;main: Now I can quit.&quot;)<br>}</pre><p>In this function, I am launching 10 distinct coroutines and giving a delay of 500 milliseconds for each iteration, and also parallel (as the code is asynchronous, it doesn&#39;t have to wait for completion), giving a delay of 2000 milliseconds (2 seconds), and canceling the child coroutine immediately</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*gCj82oL0V4BJJUQQccjOeQ.png" /></figure><p>The above is the output for that function. How the child&#39;s job got terminated is by the <strong>delay() </strong>function,<strong> </strong>which checks for the cancellation internally ( basically it checks if the coroutine is in Active state and cancels further operation) and throws <strong>CancellationException,</strong> which further stops the Loop since no try/catch block is added the exception was not caught and terminates the child job.</p><p>from the below source code of <strong><em>delay()</em></strong> we can confirm it throws an <strong>exception</strong></p><pre>if (job != null &amp;&amp; !job.isActive) {<br>    val cause = job.getCancellationException()<br>    cancelResult(state, cause)<br>    throw recoverStackTrace(cause, this)<br>}</pre><p>The above example was for cooperative cancellation. However, if a coroutine is working on computations without checking for cancellation, then it cannot be cancelled at all</p><p>like the example below</p><pre>fun withoutCooperation() = runBlocking {<br>    val startTime = currentTimeMillis()<br>    val job = launch(Dispatchers.IO) {<br>        var nextPrintTime = startTime<br>        var i = 0<br>        while (i &lt; 30) {<br>            if (currentTimeMillis() &gt;= nextPrintTime) {<br>                println(&quot;job: I&#39;m sleeping ${i++} ...&quot;)<br>                nextPrintTime += 1000L<br>            }<br>        }<br>    }<br>    delay(1000L) // delay a bit<br>    job.cancel()<br>    println(&quot;man: I&#39;m tired of waiting!&quot;)<br>    println(&quot;man: Now I can quit.&quot;)<br>}</pre><p>In the above function, trying to simulate a delay of 1000 milliseconds inside a loop, and canceling the child job after 1000 milliseconds. Even though we cancel the child job, the loop keeps on running, as there is no coroutine cancellation check</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*PLJP6OyqCghN993fyOZvrA.png" /></figure><p>The above is the output. We can see here that iteration continues further even after the explicit cancellation of the child job, so to discontinue the computation, we have to check for the cancellation of the coroutine</p><p>Below is the code that checks for the cancellation</p><pre>fun withoutCooperation() = runBlocking {<br>    val startTime = currentTimeMillis()<br>    val job = launch(Dispatchers.IO) {<br>        var nextPrintTime = startTime<br>        var i = 0<br>        while (i &lt; 30 &amp;&amp; isActive) {<br>            if (currentTimeMillis() &gt;= nextPrintTime) {<br>                println(&quot;job: I&#39;m sleeping ${i++} ...&quot;)<br>                nextPrintTime += 1000L<br>            }<br>        }<br>    }<br>    delay(1000L) // delay a bit<br>    job.cancel()<br>    println(&quot;man: I&#39;m tired of waiting!&quot;)<br>    println(&quot;man: Now I can quit.&quot;)<br>}</pre><p>have added <strong><em>isActive </em></strong>check<strong><em> </em></strong>inside the computation loop,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*QoMcR_hhIQ3jmTdwhDZFmw.png" /></figure><p>From he output, we can see the interaction discontinues the computation as soon as we cancel the job</p><p>That&#39;s it with part 1, I will explore more topics such as kotlin coroutines with <strong>Jetpack Libraries</strong> in upcoming parts, and other suspending functions <br>Thanks for reading, I hope it helps :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb46f7a246d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Flow Retry and RetryWhen extension functions]]></title>
            <link>https://nsagarrock.medium.com/kotlin-flow-retry-and-retrywhen-extension-functions-a2bf9f273fa5?source=rss-7492b4f1c2b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2bf9f273fa5</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Sagar N]]></dc:creator>
            <pubDate>Sun, 01 Aug 2021 14:29:00 GMT</pubDate>
            <atom:updated>2021-08-01T14:29:00.423Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will be writing about using Kotlin flow extension function for retrying network calls</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXAe_G_QpjwQl4sDVwPqmQ.jpeg" /></figure><h4>Why do we need this</h4><p>In cases</p><ul><li>where there are low bandwidth connections and high latency connections</li><li>Token authentication failure</li><li>uncertain network</li></ul><p>We need to retry network calls for Important APIs such as Sign In, Sign Up, Log In (or any other API based on requirement and importance) several times due to the above cases. if not this might impact user experience.</p><h4><strong>What is flow?</strong></h4><ul><li>It is a stream of data from upstream (Input) to downstream (output) which can be computed asynchronously.</li><li>In this case, upstream would be network response, and downstream is where we show the response on UI (Activities/Fragments)</li></ul><h4>What is a coroutine?</h4><p>They are lightweight threads.</p><h4>What is suspend function?</h4><p>These are the function that can execute Long-running tasks wait for it to complete without blocking</p><h4>Dependency Needed</h4><p><strong>For Kotlin coroutines android</strong></p><p>At the time of writing, this article version is 1.5.1</p><blockquote>implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1’</blockquote><h4>Retry</h4><p>Will be taking a simple example to showcase how we can retry normal long-running task and would later provide an example of how we can use this function to retry API calls using MVVM architecture</p><p><strong>Example:</strong></p><pre>fun startTask(): Flow&lt;Int&gt; {<br>    return <em>flow </em><strong>{<br>        </strong>for (i in 1..4) {<br>            val randomInt = (0..2).<em>random</em>()<br>            if (randomInt == 0) {<br>                throw IndexOutOfBoundsException()<br>            } else if (randomInt == 2) {<br>                throw  IOException()<br>            }<br>            emit(i)<br>        }<br>    <strong>}</strong>.<em>flowOn</em>(Dispatchers.IO)<br>}</pre><p>The above function is returning a Flow of Int values from 1 to 4 and throwing exceptions to integers 0,2 which is random. In the context of Dispatcher.IO which is a coroutines dispatcher designed for offloading blocking tasks to a shared pool of threads</p><p>I have used the flowOn(Dispatchers.IO) to mimic a real scenario as usually long running operation are executed on background thread.</p><p>Assume that the above method is a real-time API call where at times we need to retry the API call to get the response</p><p><strong>We can use the <em>retry()</em> Flow extension function like this</strong></p><pre>suspend fun main(args: Array&lt;String&gt;) {</pre><pre>    <em>startTask</em>()<br>        .<em>retry</em>(3) <strong>{<br>            </strong><em>println</em>(&quot;retrying...&quot;)<br>            delay(2000)<br>            <strong>it </strong>is IndexOutOfBoundsException<br>        <strong>}</strong>.<em>catch </em><strong>{<br>            </strong><em>print</em>(<strong>it</strong>.toString())<br>        <strong>}<br>        </strong>.collect <strong>{<br>            </strong><em>println</em>(<strong>it</strong>)<br>        <strong>}</strong></pre><pre>}</pre><ul><li>The above method is collecting the flow of int values from the upstream but also with help of retry and catch operator</li><li>The <em>retry()</em> takes in an optional parameter of type Long which signifies a number of times to retry the upstream flow till the exception occurs in the upstream flow. if it is not provided would use default Long.MAX_VALUE value</li><li>And a suspending function with throwable as its parameter and return type of boolean if it is not provided would use the default value true</li><li>The <em>catch()</em> catches the exception in the upstream flow and calls the specified action</li><li>Since <em>retry() </em>is a suspending function.<em> </em>We can introduce delays in between retry calls to have some buffer time with the help of<em> delay(timeMillis: Long) </em>which is also a suspend function.</li></ul><p><strong>The output of the above code snippet</strong></p><pre>retrying...<br>retrying...<br>retrying...<br>1<br>java.io.IOException<br>Process finished with exit code 0</pre><p>There was series of exceptions in the upstream flow and hence the messages “retrying…” meaning retrying of the upstream flow</p><p>There was no exception in the upstream flow and hence 1 is printed</p><p>Later there was a different exception in the upstream flow than the one specified in the lambda expression and also a number of retries are empty and hence it is caught using catch and the exception caught is printed</p><p><strong>Below code is taken from Error.kt file of kotlinx.coroutines.flow package</strong></p><pre>public fun &lt;T&gt; Flow&lt;T&gt;.retry(<br>    retries: Long = Long.MAX_VALUE,<br>    predicate: suspend (cause: Throwable) -&gt; Boolean = <strong>{ </strong>true <strong>}<br></strong>): Flow&lt;T&gt; {<br>    <em>require</em>(retries &gt; 0) <strong>{ </strong>&quot;Expected positive amount of retries, but had $retries&quot; <strong>}<br>    </strong>return <em>retryWhen </em><strong>{ </strong>cause, attempt <strong>-&gt; </strong>attempt &lt; retries &amp;&amp; predicate(cause) <strong>}<br></strong>}</pre><p><em>retry() </em>internal calls<em> retryWhen()</em> function only after a check if the number of retries is more than zero if not an IllegalArgumentException would be thrown which would cancel the flow and with the message the “Expected positive amount of retries, but had $retries”</p><p>Connecting with the above example<strong> [predicate]</strong> is the lambda expression</p><pre><strong>{<br>    </strong><em>println</em>(&quot;retrying...&quot;)<br>    delay(2000)<br>    <strong>it </strong>is IndexOutOfBoundsException<br><strong>}</strong></pre><p><strong>it</strong> is the throwable passed when predicate: <strong>suspend (cause: Throwable)</strong> is invoked inside <em>retry(</em>)</p><p><strong>RetryWhen</strong></p><p>Retires the collection of upstream flow till there is an exception occurring in the upstream flow and also when the predicate function returns true.</p><p>modifying the above example to use <em>retryWhen()</em></p><pre><em>startTask</em>()<br>    .<em>retryWhen </em><strong>{ </strong>cause, attempt <strong>-&gt;<br>        </strong><em>println</em>(&quot;retrying...&quot;)<br>        delay(2000)<br>        attempt &lt; 3 || cause is IOException<br>    <strong>}</strong>.<em>catch </em><strong>{<br>        </strong><em>print</em>(<strong>it</strong>.toString())<br>    <strong>}<br>    </strong>.collect <strong>{<br>        </strong><em>println</em>(<strong>it</strong>)<br>    <strong>}</strong></pre><p><strong>The output of the above code snipped</strong></p><pre>retrying...<br>1<br>retrying...<br>retrying...<br>retrying...<br>java.lang.IndexOutOfBoundsException</pre><p>Here for the first time, there is an exception that occurred in the upstream flow so the message “retrying…”</p><p>1 is printed since no exception in the upstream</p><p>Initially, attempt would be 0, and since 0 &lt; 3 returning true to the lambda expression indicating to retry again the upstream till attempt reaches 3</p><pre>attempt &lt; 3</pre><p>Let&#39;s look at how internally <em>retryWhen()</em> is implemented.</p><p><strong>Below is the code taken from Error.kt file of kotlinx.coroutines.flow package</strong></p><pre>public fun &lt;T&gt; Flow&lt;T&gt;.retryWhen(predicate: suspend FlowCollector&lt;T&gt;.(cause: Throwable, attempt: Long) -&gt; Boolean): Flow&lt;T&gt; =<br>    <em>flow </em><strong>{<br>        </strong>var attempt = 0L<br>        var shallRetry: Boolean<br>        do {<br>            shallRetry = false<br>            val cause = catchImpl(this)<br>            if (cause != null) {<br>                if (predicate(cause, attempt)) {<br>                    shallRetry = true<br>                    attempt++<br>                } else {<br>                    throw cause<br>                }<br>            }<br>        } while (shallRetry)<br>    <strong>}</strong></pre><ul><li><em>retryWhen() </em>takes a suspend function which has two parameters cause of type throwable and attempt of type Long</li><li>cause is the exception occurred in the upstream flow</li><li>attempt is the number of attempts made to retry the upstream flow</li><li>This function returns the flow to downstream</li><li>It has attempt which is an internal variable that would be incremented inside the do-while loop</li><li>It has shallRetry which is also an internal variable a boolean flag to allow the loop to run until the lambda function returns false (as <strong>predicate(cause, attempt)</strong>)</li><li><em>cathchImp() </em>function which takes in FlowCollector interface. Checks and returns the exception from upstream or null.</li><li>While checking with the upstream flow exception c<em>atchImp() </em>each time<em> </em>internally triggers the upstream flow using collect suspend function of the Flow Interface.</li></ul><p>For the first time attempt would be 0, shallRetry false</p><p>Assume there is an exception in upstream then exception (as <strong>cause)</strong> is passed to the lambda function (as <strong>predicate</strong>). Connecting with the example this would be the lambda expression</p><pre><strong>{ </strong>cause, attempt <strong>-&gt;<br>    </strong><em>println</em>(&quot;retrying...&quot;)<br>    delay(2000)<br>    attempt &lt; 3 || cause is IOException<br><strong>}</strong></pre><p>returns boolean based on this condition (attempt &lt; 3 || cause is IOException) to here</p><pre>if (<strong>predicate(cause, attempt)</strong>) {<br>     shallRetry = true<br>     attempt++<br>   } else {<br>    throw cause<br>  }</pre><p>shallRetry would be true and the attempt would be incremented inside the If block</p><p>The loop repeats until the above condition satisfies if not the exceptions from upstream are thrown to downstream and need to be handled accordingly.</p><p><strong>Example with MVVM architecture</strong></p><p><em>TopHeadlinesService.kt</em></p><pre>@GET(&quot;top-headlines&quot;)<br>suspend fun getTopHeadlines(<br>    @Query(&quot;country&quot;) country: String<br>): TopHeadlines</pre><p>This is a remote service class that has a suspending function named getTopHealines() which would return TopHeadlines response.</p><p><em>TopHeadlinesRemoteSource.kt</em></p><pre>suspend fun getNewsHeadLines(country: String): Flow&lt;TopHeadlines&gt; {<br>    return <em>flow </em><strong>{<br>        </strong>emit(newsHeadlinesService.getTopHeadlines(country))<br>    <strong>}</strong>.<em>flowOn</em>(Dispatchers.IO)<br>}</pre><p>This above function is part of the remote source class which returns the response from the service class as a stream of response data in the context of Dispatchers.IO asynchronously</p><p><em>TopHeadlinesRepo.kt</em></p><pre>fun getNewsHeadlines(country: String): LiveData&lt;DataWrapper&lt;TopHeadlines&gt;&gt; {<br>    return <em>liveData </em><strong>{<br>        </strong>emit(DataWrapper.loading(null))<br>        remoteSource.getNewsHeadLines(country).<em>retry</em>(3) <strong>{<br>            </strong>delay(NETWORK_RETRY_DELAY)<br>            return@retry true<br>        <strong>}</strong>.<em>catch </em><strong>{<br>            </strong>emit(DataWrapper.error(<strong>it</strong>.message.<em>toString</em>()))<br>        <strong>}</strong>.collect <strong>{<br>            </strong>emit(DataWrapper.success(<strong>it</strong>))<br>        <strong>}<br>    }<br></strong>}</pre><p>The above function is part of the repo class which converts the flow of data from upstream to live data. Here I am using the <em>retry()</em> flow extension function. After 3 retries with delay and if still an exception is thrown I am catching it and converting it to a custom error data class</p><p><em>NewsViewMode.kt</em></p><pre>val newsHeadLinesLD = newsHeadLinesMLD.<em>switchMap </em><strong>{<br>    </strong>if (<strong>it</strong>.category.<em>isEmpty</em>())<br>        newsHeadlinesRepo.getNewsHeadlines(<strong>it</strong>.country)<br>    else {<br>        newsHeadlinesRepo.getNewsHeadlines(<strong>it</strong>.country, <strong>it</strong>.category)<br>    }<br><strong>}</strong></pre><p>Observing the liveData in Fragment as shown below:</p><pre>viewModel.newsHeadLinesLD.observe(<em>viewLifecycleOwner</em>, <em>Observer </em><strong>{<br>    </strong>when (<strong>it</strong>.status) {<br>        DataWrapper.Status.<em>LOADING </em>-&gt; {}<br>        DataWrapper.Status.<em>SUCCESS </em>-&gt; {}<br>        DataWrapper.Status.<em>ERROR </em>-&gt; {}<br><strong>}</strong>)</pre><p>This is the Flow way of retrying network calls. Thank you for reading the article I hope it helps :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2bf9f273fa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView With Multi-View Types]]></title>
            <link>https://nsagarrock.medium.com/recyclerview-with-multi-view-types-1c746857f913?source=rss-7492b4f1c2b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c746857f913</guid>
            <category><![CDATA[mvvm-databinding]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[multiple-viewholder]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[beginner-developers]]></category>
            <dc:creator><![CDATA[Sagar N]]></dc:creator>
            <pubDate>Sat, 07 Nov 2020 12:11:27 GMT</pubDate>
            <atom:updated>2020-11-07T16:40:27.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*mfQO-dEziUUG4N2Bdj__mA.gif" /></figure><p>In this article, I will talk about how we can use recyclerView with multiple view types</p><h3><strong>Things you need:</strong></h3><ul><li>Data Binding enabled in your project (It can also be done without data binding but adding it will be useful)</li><li>Constants for different view types</li><li>An abstract class with an abstract method</li><li>ViewHolder classes for different view types</li><li>Overriding getItemViewType() method inside Adapter Class</li></ul><p><strong>To Enable DataBinding in your project</strong></p><ul><li>In the app-level Gradle file add this android plugin</li></ul><pre>apply plugin: &#39;kotlin-kapt&#39;</pre><ul><li>Inside the android block add the below line</li></ul><pre>dataBinding <strong>{<br>    </strong>enabled = true<br><strong>}</strong></pre><ul><li>In order to convert any layout file to its data binding equivalent</li><li>Right-click on the root tag in the XML file of the layout</li><li>And click on show context actions and then choose convert to data binding layout</li></ul><h4><strong>Constants for different view types</strong></h4><p>For this example, I have created two different layouts and have two constants fields to differentiate between the view types (will be using them while overriding the getItemViewType() and onCreateViewHolder() methods)</p><pre>private const val <em>TYPE_IMAGE </em>= 0<br>private const val <em>TYPE_HEADER </em>= 1</pre><p>These are the two different item’s layout which I would specify for inflation in the Adapter Class</p><ol><li>item_image.xml</li></ol><pre>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br><br>    &lt;data&gt;<br><br>    &lt;/data&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;&gt;<br>        &lt;ImageView<br>            android:id=&quot;@+id/iv_img&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;300dp&quot;<br>            android:src=&quot;@drawable/sunset_uyuni&quot;<br>            android:layout_marginStart=&quot;20dp&quot;<br>            android:layout_marginEnd=&quot;20dp&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            /&gt;<br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/layout&gt;</pre><p>2. item_header_text.xml</p><pre>&lt;layout 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;&gt;</pre><pre>    &lt;data&gt;</pre><pre>    &lt;/data&gt;</pre><pre>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;&gt;<br>        &lt;TextView<br>            android:id=&quot;@+id/tv_header&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            tools:text=&quot;Header&quot;<br>            android:textSize=&quot;24sp&quot;<br>            android:textColor=&quot;@color/white&quot;<br>            android:textStyle=&quot;bold&quot;<br>            android:fontFamily=&quot;serif-monospace&quot;<br>            android:layout_marginStart=&quot;10dp&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            /&gt;<br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/layout&gt;</pre><h4>An abstract class with an abstract method</h4><ul><li>We need this abstract class to extend RecyclerView.ViewHolder class and pass binding.root (which is the root view of the data binding layout) as a constructor</li><li>We would extend this abstract class and implement the bind() method inside our ViewHolder Classes</li></ul><pre>abstract class ItemViewHolder&lt;T&gt;(binding: ViewDataBinding) :<br>    RecyclerView.ViewHolder(binding.<em>root</em>) {<br>    abstract fun bind(item: T)<br>}</pre><h4>ViewHolder Classes for Different View Types</h4><ul><li>ViewHolder for the header text which is TextView type</li></ul><pre>inner class HeaderTextViewHolder(private val binding: ItemHeaderTextBinding) :<br>    ItemViewHolder&lt;Data&gt;(binding) {<br>    override fun bind(item: Data) {<br>        binding.tvHeader.<em>text </em>= item.headerText<br>    }<br>}</pre><ul><li>ViewHolder for the images seen in the Gif which is ImageView type</li></ul><pre>inner class ImageViewHolder(private val binding: ItemImageBinding) :<br>    ItemViewHolder&lt;Data&gt;(binding) {<br>    override fun bind(item: Data) {<br>        itemView<br>        binding.ivImg.setImageResource(item.imgRes)<br>    }<br>}</pre><h4>Overriding getItemViewType() method inside the Adapter Class</h4><ul><li>Since we want different view types we need to override the getItemViewType and then return the type of view we want the onCreateViewHolder() to create the view holder for that type</li><li>The getItemViewType() method will be called before onCreateViewHolder() method internally</li><li>If we don&#39;t override the getItemeViewType(), it makes the assumption of<br> a single view type for the adapter</li><li>We get the position in the getItemViewType() method which can be used to know what ViewHolder do we want to get created</li></ul><pre>override fun getItemViewType(position: Int): Int {<br>    var value: Int<br>    var item = list[position]<br>    value = when (item.type) {<br>        context.getString(R.string.<em>header_type</em>) -&gt; <em>TYPE_HEADER<br>        </em>context.getString(R.string.<em>img_type</em>) -&gt; <em>TYPE_IMAGE<br>        </em>else -&gt; <em>TYPE_IMAGE<br>    </em>}<br><br>    return value<br>}</pre><p>I am using a dummy data class called Data.kt</p><pre>data class Data(var headerText: String, var imgRes: Int, var type: String)</pre><p>which has the field to determine what type</p><ul><li>Lastly we need to also check for the viewType parameter in both onCreateViewHolder() and onBindViewHolder() called by RecyclerView to display the data at the specified position</li></ul><h4>The whole Adapter class for reference:</h4><pre>private const val <em>TYPE_IMAGE </em>= 0<br>private const val <em>TYPE_HEADER </em>= 1<br>class MultiTypeAdapter(private val context: Context) :<br>    RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() {<br><br>    private var list = ArrayList&lt;Data&gt;()<br><br>    private var parent: ViewGroup? = null<br><br>    private fun &lt;T : ViewDataBinding&gt; binder(layout: Int): T {<br>        return DataBindingUtil.inflate&lt;T&gt;(<br>            LayoutInflater.from(parent?.<em>context</em>)!!,<br>            layout, parent, false<br>        )<br>    }<br><br>    fun setData(list: ArrayList&lt;Data&gt;) {<br>        this.list = list<br>        notifyDataSetChanged()<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder&lt;Data&gt; {<br>        this.parent = parent<br>        return when (viewType) {<br>            <em>TYPE_IMAGE </em>-&gt; {<br>                val binding: ItemImageBinding = binder(R.layout.<em>item_image</em>)<br>                ImageViewHolder(binding)<br>            }<br>            <em>TYPE_HEADER </em>-&gt; {<br>                val binding: ItemHeaderTextBinding = binder(R.layout.<em>item_header_text</em>)<br>                HeaderTextViewHolder(binding)<br>            }<br>            else -&gt; throw IllegalArgumentException()<br>        }<br>    }<br><br>    override fun getItemCount() = list.size<br><br>    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>        val item = list[position]<br>        when (holder) {<br>            is ImageViewHolder -&gt; holder.bind(item)<br>            is HeaderTextViewHolder -&gt; holder.bind(item)<br>        }<br>    }<br><br>    override fun getItemViewType(position: Int): Int {<br>        var value: Int<br>        var item = list[position]<br>        value = when (item.type) {<br>            context.getString(R.string.<em>header_type</em>) -&gt; <em>TYPE_HEADER<br>            </em>context.getString(R.string.<em>img_type</em>) -&gt; <em>TYPE_IMAGE<br>            </em>else -&gt; <em>TYPE_IMAGE<br>        </em>}<br><br>        return value<br>    }<br><br>    abstract class ItemViewHolder&lt;T&gt;(binding: ViewDataBinding) :<br>        RecyclerView.ViewHolder(binding.<em>root</em>) {<br>        abstract fun bind(item: T)<br>    }<br><br>    inner class ImageViewHolder(private val binding: ItemImageBinding) :<br>        ItemViewHolder&lt;Data&gt;(binding) {<br>        override fun bind(item: Data) {<br>            itemView<br>            binding.ivImg.setImageResource(item.imgRes)<br>        }<br>    }<br><br>    inner class HeaderTextViewHolder(private val binding: ItemHeaderTextBinding) :<br>        ItemViewHolder&lt;Data&gt;(binding) {<br>        override fun bind(item: Data) {<br>            binding.tvHeader.<em>text </em>= item.headerText<br>        }<br>    }<br>}</pre><p>Thanks for reading this article I hope it helps :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c746857f913" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView with single item selection]]></title>
            <link>https://nsagarrock.medium.com/recyclerview-with-single-item-selection-a6db8e2839d8?source=rss-7492b4f1c2b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6db8e2839d8</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[drawables]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-beginner]]></category>
            <category><![CDATA[recyclerview-selection]]></category>
            <dc:creator><![CDATA[Sagar N]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 08:40:15 GMT</pubDate>
            <atom:updated>2020-04-19T08:40:15.966Z</atom:updated>
            <content:encoded><![CDATA[<p>If you wanted to achieve something like this</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FH6JY2JqXSiQuQagVg3%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FH6JY2JqXSiQuQagVg3%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="870" frameborder="0" scrolling="no"><a href="https://medium.com/media/3de58f63cb67cce5257e1fe1bd9856f6/href">https://medium.com/media/3de58f63cb67cce5257e1fe1bd9856f6/href</a></iframe><h3>Single item selection can be maintained in RecyclerView by</h3><ul><li>Two variables to be kept updated when an item is selected</li><li>The first variable maintains the currently selected position</li><li>The second variable maintains the last selected position</li><li>Two different background drawable for the selected and unselected items</li><li>Two methods in ViewHolder Class to change the background of items</li></ul><h3>Background drawable</h3><p>For the item selected in my example:</p><p>Drawable name: bg_capsule_selected</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:shape=&quot;rectangle&quot;&gt;<br><br>    &lt;corners<br>     android:radius=&quot;300dp&quot; /&gt;<br><br>    &lt;stroke<br>        android:width=&quot;1dp&quot;<br>        android:color=&quot;@color/white&quot; /&gt;<br><br>    &lt;solid android:color=&quot;@color/colorOffGreen&quot; /&gt;<br>&lt;/shape&gt;</pre><p>For the item unselected</p><p>Drawable name: bg_capsule_unselected</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:shape=&quot;rectangle&quot;&gt;<br>    &lt;corners<br>     android:radius=&quot;300dp&quot; /&gt;<br>    &lt;stroke<br>        android:width=&quot;1dp&quot;<br>        android:color=&quot;#11B8B7BA&quot; /&gt;<br>    &lt;solid android:color=&quot;#F3F3F4&quot; /&gt;<br>&lt;/shape&gt;</pre><h3>Variables</h3><p>Two variables to be initialized in your Adapter Class</p><pre>var selectedItemPos = -1<br>var lastItemSelectedPos = -1</pre><p>Separate methods in the ViewHolder Class for changing the background of the items when selected and unselected</p><pre>fun defaultBg() {<br>    binding.tvCurrencyName.<em>background </em>= context.getDrawable(R.drawable.<em>bg_capsule_unselected</em>)<br>}<br><br>fun selectedBg() {<br>    binding.tvCurrencyName.<em>background </em>= context.getDrawable(R.drawable.<em>bg_capsule_selected</em>)<br>}</pre><h3>Logic</h3><p>The logic is to update the variables and calling the notifyItemChange(position) which would then call the method onBindViewHolder(holder: ViewHolder, position: Int) for this to happen we have to initialize the click listener for each of the itemViews and update the variables accordingly with the <em>adapter position</em> and<em> </em>call notifyItemChange() method with passing the item position to change</p><pre>init {<br>    itemView.setOnClickListener <strong>{<br>        </strong>selectedItemPos = <em>adapterPosition<br>        </em>if(lastItemSelectedPos == -1)<br>            lastItemSelectedPos = selectedItemPos<br>        else {<br>            notifyItemChanged(lastItemSelectedPos)<br>            lastItemSelectedPos = selectedItemPos<br>        }<br>        notifyItemChanged(selectedItemPos)<br>    <strong>}<br></strong>}</pre><p>this code is written inside the ViewHolder Class as an init block Since we have set click listeners for every itemView and then when we call notifyItemChange() method would call onBindViewHolder() method and in this method, we would check for the position and change their background with the help of two methods written inside ViewHolder Class like this</p><pre>override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>    if(position == selectedItemPos)<br>        holder.selectedBg()<br>    else<br>        holder.defaultBg()<br>    holder.bindItems(adapterList[position])<br>}</pre><p>lastly set supportChangeAnimations to false so that there would be no blink or flicker effects on items of RecyclerView when clicked</p><pre>(rvCurrency.<em>itemAnimator </em>as SimpleItemAnimator).<em>supportsChangeAnimations </em>= false</pre><p>Thanks for reading this article I hope it helps :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6db8e2839d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>