<?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 Gaurav Chaddha on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Chaddha on Medium]]></description>
        <link>https://medium.com/@chaddhag?source=rss-449c72129f69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CjrDKPSwNxatHqDUrDhGww.jpeg</url>
            <title>Stories by Gaurav Chaddha on Medium</title>
            <link>https://medium.com/@chaddhag?source=rss-449c72129f69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:06:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chaddhag/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[Wireless ADB flow for easier development]]></title>
            <link>https://chaddhag.medium.com/wireless-adb-flow-for-easier-development-49fcde140d2c?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/49fcde140d2c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[adb]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 10:27:27 GMT</pubDate>
            <atom:updated>2021-04-16T10:28:48.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHm52h5rZAh946bCQc1WzQ.jpeg" /></figure><p>This is a guide for wireless adb debugging flow without needing to connect your device to your PC all the time. I’ve included steps and information to help non-android engineers (e.g. backend engineers, data analysts) setup adb for easier development.</p><p>This post was originally published at <a href="https://www.chaddha.me/wirless-adb/">https://www.chaddha.me/wirless-adb</a></p><h3>Beginner section</h3><p>In case you are a seasoned android engineer, jump past the beginner section to “<strong>Connect to a device over Wifi</strong>”.</p><p>In case you are not an android engineer, you most likely don’t have the tools installed or correct settings on your device. Let’s setup them first.</p><h3>What is adb?</h3><p>Android Debug Bridge (adb) is a versatile command-line tool that lets you communicate with a device. The adb command facilitates a variety of device actions, such as installing and debugging apps.</p><h3>Step 1: Installing adb</h3><p>To install adb on macOS, the easiest way is to use homebrew. <a href="https://brew.sh/">Homebrew</a> is a package manager for macOS. If you don’t have homebrew install, use this command to install:</p><pre>/bin/bash -c &quot;$(curl -fsSL <a href="https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh">https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh</a>)&quot;</pre><p>To install adb using homebew, run this command</p><pre>brew install android-platform-tools</pre><p>For other OS like windows or linux, you can check this <a href="https://www.xda-developers.com/install-adb-windows-macos-linux/">guide</a>.</p><h3>Steps 2: Turning on Developer options</h3><p>To connect your device to a PC and use adb, we must turn on the Developer options on device. This setting lets you configure system behaviors that help you profile and debug your app.</p><p>To turn developer options on, you have to find <strong>Build Number</strong> option in settings and tap on it <strong>7 times</strong>. You can find this option in one of the following locations, depending on your Android version and device brand:</p><ul><li>Android 9 and higher: <strong>Settings &gt; About Phone &gt; Build Number</strong></li><li>Android 8 : <strong>Settings &gt; System &gt; About Phone &gt; Build Number</strong></li><li>Android 7 and lower: <strong>Settings &gt; About Phone &gt; Build Number</strong></li></ul><p>Once you do this, you should be able to see Developer options setting at one of the following locations, depending on your Android version and device</p><ul><li>Android 9 and higher: <strong>Settings &gt; System &gt; Advanced &gt; Developer Options</strong></li><li>Android 8: <strong>Settings &gt; System &gt; Developer Options</strong></li><li>Android 7 and lower: <strong>Settings &gt; Developer Options</strong></li></ul><h3>Step 3: Turning on USB debugging</h3><p>Before you can use the debugger and other tools, you need to enable USB debugging, which allows adb to recognize your device when connected via USB. To enable USB debugging, toggle the <strong>USB debugging</strong> option in the Developer Options menu.</p><h3>Step 4: Connecting your device</h3><p>Once you have installed adb, turned on developer options and USB debugging, connect your phone via a cable to your PC. As soon as you connect your device, you may see a popup on your devices with the title “<strong>Allow USB debugging</strong>” showing the RSA fingerprint of your PC, check the “Always trust this computer” option if it is your personal PC, and press Ok.</p><h3>Step 5: Check the connection</h3><p>Run the following command to list the devices connected</p><pre>adb devices</pre><p>You should see an output as shown<br>(If you don’t, that means your device isn’t connected to your PC — check your cable connection)</p><pre>Output:<br>List of devices attached<br>[Device Name]	device</pre><p>This marks the end of beginner section. Now we begin the steps to connect adb over Wifi.</p><h3>Connect to a device over Wifi</h3><p>Connect your device to your PC via a USB cable and ensure both your device and PC are on the same Wifi network. Then run the following command to start adb in TCP/IP mode.</p><pre>adb tcpip 5555</pre><p>Now we need to find out the IP address your device has on the wifi network. You can either go to about section of your settings, there in status page you can see your device assigned IP address, or you can run this command which gets your network addresses for wlan0 i.e. wifi network:</p><pre>adb shell ip -f inet addr show wlan0</pre><p>This commands prints an network-info output:</p><pre>Output:<br>30: wlan0: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc mq state UP group default qlen 3000<br>    inet 192.168.1.33/24 brd 192.168.1.255 scope global wlan0<br>       valid_lft forever preferred_lft forever</pre><p>192.168.1.33 is your device IP on the WIFI network.</p><p>Now we run the command to connect to the device IP over 5555 port:</p><pre>adb connect [IP]:5555</pre><p>It gives a status output:</p><pre>Output:<br>connected to [IP]:5555</pre><p>Disconnect your USB cable and run adb devices again, you should an output like:</p><pre>List of devices attached<br>[IP]:5555	device</pre><p>This means your device is now running ADB over wifi on the 5555 port.</p><p><strong>Note: </strong><br>In my personal experience, unless your router is restarted or your device restarts, router keeps the device IP same and thus I’ve never had to connect cable for weeks even after disconnecting to the WIFI. I just needed to run adb connect [Last_IP]:5555 to connect to my device without attaching the cable again.</p><p><strong>Note 2: </strong><br>In case of any error or misbehaviour, run the following:</p><pre># Disconnect the device<br>adb disconnect [IP]:5555</pre><pre># This kills the adb server <br>adb kill-server</pre><pre># Restart the adb server<br>adb start-server</pre><pre># Reconnect device via cable and repeat step 6<br>adb tcpip 5555<br>adb connect [IP]:5555</pre><h3>Bonus: Installing apk using adb</h3><p>One of the most basic use-case for a non-android engineer to use adb is to install an apk. To do that one needs to run the following command after ensuring that device is connected:</p><pre>adb install -r -t -d path_to_apk</pre><p>The flags -r, -t and -d are to replace existing application, allow test packages and allow version code downgrade respectively.</p><p>You can learn more about adb commands by running adb help or by visiting <a href="https://adbshell.com/">https://adbshell.com</a>.</p><h3>Bonus: Presenting device screen on PC</h3><p>Another major use-case is to present your device screen on PC to share on a zoom meeting. To do this we install another command line utlity by Genymobile called <a href="https://github.com/Genymobile/scrcpy">scrcpy</a></p><p>Installing in macOS using homebrew is easy, just run this command:</p><pre>brew install scrcpy</pre><p>To present your device, you simply connect your device and run:</p><pre>scrcpy</pre><p>To learn more about it’s flags and capabilities, run scrcpy --help or visit their <a href="https://github.com/Genymobile/scrcpy">github page</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49fcde140d2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical concepts for Coroutines (Part 2)]]></title>
            <link>https://chaddhag.medium.com/practical-concepts-for-coroutines-part-2-709cc6061662?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/709cc6061662</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 17:55:28 GMT</pubDate>
            <atom:updated>2021-01-30T17:58:33.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5yOph-nViepOqOwZyOA7g.jpeg" /></figure><p><em>Originally published at </em><a href="https://www.chaddha.me/practical-concept-coroutines-2/"><em>https://www.chaddha.me/practical-concept-coroutines-2/</em></a><em> on Dec 26, 2020.</em></p><p>This article covers the practical concepts for using coroutines in actual projects, different use-cases that arise, while showing the code in action to explain the concepts clearly.</p><p>If you are looking for some concepts not covered here — check the first <a href="https://chaddhag.medium.com/practical-concepts-for-coroutines-part-1-95488d2b951">part</a>. If you are not comfortable with coroutine basics, I’ll suggest to read through one of my previous post where I covered the <a href="https://chaddhag.medium.com/kotlin-coroutines-fundamentals-9aff1e1898bc">fundamentals of coroutines</a>.</p><h3>Table of content</h3><ol><li>Converting callback to coroutines</li><li>Custom coroutine scope</li><li>Supervisor job and scope</li><li>Exception handling<br>4.1 1st Behaviour<br>4.2 2nd Behaviour<br>4.3 Notable points</li><li>Structured concurrency<br>5.1 Parent job is cancelled<br>5.2 Dependency sibling job failure</li><li>Integration with Retrofit</li></ol><h3>Converting callback to coroutines</h3><p>Many times we are using libraries which doesn’t support coroutines yet, for that we need to wrap the callback into a suspend f(). Coroutine library provide an extension f() ‘<strong><em>suspendCancellableCoroutine</em></strong><em>’</em>.</p><p>It takes in a suspend block it’ll execute. Just like <em>withContext</em> it’ll suspend the calling coroutine until we invoke resume f()s from inside it.</p><p>Lets consider an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfb27f9fa05c5d2da3e07815d384cfef/href">https://medium.com/media/dfb27f9fa05c5d2da3e07815d384cfef/href</a></iframe><p>Here we have a callback interface and some f() that does some asynchronous work for us and takes a callback.</p><p>Lets see how we can wrap someTask in a coroutine world easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3e286432b0a2581322df083666a8f80/href">https://medium.com/media/b3e286432b0a2581322df083666a8f80/href</a></iframe><p>And now we can use it in any coroutine as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6b93b011d861e0fa38706505acd656/href">https://medium.com/media/df6b93b011d861e0fa38706505acd656/href</a></iframe><h3>Custom coroutine scope</h3><p>If we need to create a custom coroutine scope in a function, we can use the ‘<em>coroutineScope(block: suspend CoroutineScope.() -&gt; R): R’ </em>f () provided by the coroutine library. <em>coroutineScope</em>() doesn’t block the calling thread when it launches a new coroutine but it’ll suspend the parent job. <br>i.e. Just like <em>withContext</em> the calling f() doesn’t execute further until coroutineScope block doesn’t finish executing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aad86071738ac5845c9fb81a6a5f701/href">https://medium.com/media/2aad86071738ac5845c9fb81a6a5f701/href</a></iframe><p>I’ve been unable to find a use-case where I have to make a custom coroutine scope like this that I can’t achieve via normal builders. If you know any use-cases for it, please comment.</p><h3>Supervisor job and scope</h3><p>A fact that i’ve not revealed until now is that, if there is an exception in any child job of a parent job, then the parent job is cancelled as well.</p><p>For e.g. if parent1 had three child jobs — child1,child2, child3. <br>If child1 fails with an exception, then parent1 will also fail causing child2 and child3 to stop as well.</p><p>But what if we don’t want parent1, child2 and child3 to fail if child1 does?<br>For that we can use a <strong>SupervisorJob</strong> instead of a normal job as parent. <br><strong>SupervisorJob</strong> ensures that if one of it’s child fails with exception, then others keep on executing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96ef5348a5082768a24d80a63590694d/href">https://medium.com/media/96ef5348a5082768a24d80a63590694d/href</a></iframe><p><strong>Bonus:</strong> <em>ViewModelScope</em> by default uses a <em>SupervisorJob</em>, due to which if one operation is met with a failure, the other child coroutines aren’t affected.</p><p>A <strong><em>supervisorScope</em></strong> is a way to start a coroutine with supervisor job. The calling coroutine is suspended until this block completes just like withContext. It can’t be cancelled from outside since it’ll suspend the calling coroutine.</p><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f55313ba398aeeb0211edbda52ef218/href">https://medium.com/media/7f55313ba398aeeb0211edbda52ef218/href</a></iframe><p>Cancellation of a child coroutine inside a supervisor job works the same a normal job.</p><h3>Exception handling</h3><p>When doing operations inside coroutines exceptions might occur.</p><p>Different coroutine builders have different ways of handling it but broadly it can be broken as two behaviour:</p><h4>1st Behaviour</h4><p>launch offers a way to handle the exception. <br>We pass in a CoroutineExceptionHandler object when launching a coroutine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34513890893cde44e12f41dd16200417/href">https://medium.com/media/34513890893cde44e12f41dd16200417/href</a></iframe><p><strong>Note</strong>: If launch are nested then only the topmost launch will get the exception to handle. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eba6ad1c3353d5b795b128da11bfbe4/href">https://medium.com/media/4eba6ad1c3353d5b795b128da11bfbe4/href</a></iframe><h4>2nd Behaviour</h4><p>async, withContext, suspendCancellableCoroutine, coroutineScope all will bubble up the exception to the top parent coroutine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65468ec3a05ab33bccd7ad839f9c2fc2/href">https://medium.com/media/65468ec3a05ab33bccd7ad839f9c2fc2/href</a></iframe><p><strong>To summarize:</strong><br>Parent job has to handle it’s own and child jobs exceptions.</p><h4>Notable points</h4><ol><li>Since the most sensible way is to start coroutine via launch, if we catch the exception at the top most launch we can ensure that no exception passes through. This works for both normal job or supervisor job.</li><li>CoroutineExceptionHandler won’t recieve cancellation exceptions. <br>When a child coroutine is cancelled manually by a parent, a cancellation exception can be given when calling cancel(). It is expected of the parent job that if it is cancelling any of it’s child, then they should handle the situation themselves.</li><li>For a normal parent job, if multiple exceptions are thrown only the first one is reported with others as suppressed. <br>In case of Supervisor job, all exceptions are thrown one by one since siblings aren’t cancelled if one child throws an exception.</li><li>A normal parent job is given exception to handle only after all childs are complete. <br>Supervisor job is given it’s child exceptions immediately since sibling childs won’t be cancelled.</li></ol><h3>Structured concurrency</h3><p>The aim of structured concurrency put in simple terms is easy -</p><blockquote><em>Any coroutine we launch — we have to ensure that it doesn’t execute if it’s not required.</em></blockquote><p>There are numerous cases where the requirement of coroutines becomes invalid, but let’s consider the two most commons ones to understand the concept:</p><h4>Parent job is cancelled</h4><p>The simple way to ensure this in any coroutine we launch inside our parent coroutine is to handle for cancellations.</p><p>Let’s consider a code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/341f9604395393de970184155dfdccd1/href">https://medium.com/media/341f9604395393de970184155dfdccd1/href</a></iframe><p>We have to think on the following points in case of scope or parent job cancellation:</p><ul><li>Any <strong>suspend </strong>f() is automatically cancelled when scope of parent job is cancelled. i.e. no need to handle anything for suspendFunction1()</li><li>In case of scope cancellation, nothing executes anymore which means no worries for uncooperative child. But with a parent job cancellation, we have to ensure that our child coroutines are cooperative. e.g. nonCooperativeChild checks for <em>isActive</em> flag.</li><li>Functions provided by coroutines library like await() already check for parent job cancellation which makes our job easier.</li><li>Handle cancellation when <strong>converting callbacks</strong> to coroutine code using <em>suspendCancellableCoroutine</em> instead of <em>suspendCoroutine. </em><br>Since suspendCoroutine suspends on the calling coroutine, if the calling one is cancelled before it completes, this coroutine shouldn’t try to resume the original caller. Using suspendCancellableCoroutine ensures that if the calling coroutine is cancelled, so your execution is stopped as well.</li></ul><p><strong>In summary</strong>, to ensure you only do work when required:</p><ul><li>No worries for suspend f()s or async coroutines</li><li>Remember to use isActive if you are doing a continous loop behaviour inside child coroutines</li><li>Use <em>suspendCancellableCoroutine </em>for converting callbacks to coroutines.</li></ul><h4>Dependency sibling job failure</h4><p>Sometimes we have cases where we have to combine results from multiple tasks, but if one job fails, our computation as a whole fails. Maybe we have to combine result from API1 and API2 to show some UI. If either of them fails, we want to show a failed UI.</p><p>For such cases launch a parent job with exception handling to show failed UI then use two child coroutines to get result, prefer <em>async</em> builder. If either of the child fails, the parent job will recieve the exception and will show the failed ui.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ad3c3541851bec9f409bd589e13cb9a/href">https://medium.com/media/9ad3c3541851bec9f409bd589e13cb9a/href</a></iframe><h3>Integration with Retrofit</h3><p>Most of us use retrofit to make our network calls. We define a simple service in an interface for us to consume. Converting retrofit normal calls to coroutines is easy. <br>Consider the following service you are familiar with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98c5482c0558b4a3960cf4652a97e1c2/href">https://medium.com/media/98c5482c0558b4a3960cf4652a97e1c2/href</a></iframe><p>Now to convert it into a coroutine suspend call, simply mark the function suspend return your response directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86ec18db5b4885cddb395ddf75b367e9/href">https://medium.com/media/86ec18db5b4885cddb395ddf75b367e9/href</a></iframe><p>The suspend call to our service will automatically wait for the network call to be complete. In case of any error or exception, it is thrown in the coroutine and can be caught in the exception handler we pass.</p><p>That’s it :)<br>With all these concepts now clear, it should be easy to fit coroutines in the big picture and use it in daily work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709cc6061662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical concepts for Coroutines (Part 1)]]></title>
            <link>https://chaddhag.medium.com/practical-concepts-for-coroutines-part-1-95488d2b951?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/95488d2b951</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 17:30:36 GMT</pubDate>
            <atom:updated>2021-01-30T18:11:10.243Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ExV-RFJmYjWZc7yh60gaA.png" /></figure><p><em>Originally published at </em><a href="https://www.chaddha.me/practical-concept-coroutines-1/"><em>https://www.chaddha.me/practical-concept-coroutines-1/</em></a><em> on Dec 26, 2020.</em></p><p>This article covers the practical concepts for using coroutines in actual projects, different use-cases that arise, while showing the code in action to explain the concepts clearly.</p><p>This article covers the practical concepts for using coroutines in actual projects, different use-cases that arise, whie showing the code in action to explain the concepts clearly.</p><p>If you are not comfortable with coroutine basics, I’ll suggest to read through one of my previous post where I covered the <a href="https://chaddhag.medium.com/kotlin-coroutines-fundamentals-9aff1e1898bc">fundamentals of coroutines</a>.</p><h3>Table of content</h3><ol><li>Scopes<br> 1.1 ViewModelScope<br> 1.2 LifecycleScope</li><li>Coroutine cancellation<br>2.1 Parent job is cancelled<br>2.2 Child job is cancelled<br>2.3 Child job co-operation<br>2.4 Scope is cancelled<br>2.5 Handling resources</li><li>Timeout handling</li><li>Switching context</li><li>Next part</li></ol><h3>Scopes</h3><p>Kotlin provides GlobalScope to us — a scope lasts the lifetime of an app. Coroutines on this scope run like daemon threads — they die with the application. For android architecture components, we already have some scopes provided.</p><h4>ViewModelScope</h4><p>A <strong>ViewModelScope</strong> is defined for each ViewModel in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared.<br>We access this scope by the variable <em>`viewModelScope`.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c192fb31320072b5c83b5ef8c9486d8e/href">https://medium.com/media/c192fb31320072b5c83b5ef8c9486d8e/href</a></iframe><p>The viewModelScope by default is on Dispatcher.Main. I want to modify <em>viewModelScope</em> to achieve two things -</p><ol><li>It runs on background thread by default i.e. I don’t have to write ‘<em>viewModelScope.launch(Dispatcher.Default)’</em> every time. Since most of the time, my primary use case is doing network calls, or computation or curation in view model.</li><li>I don’t want to write ‘<em>viewModelScope.launch’</em> every time. It’s too verbose.</li></ol><p>Remember Coroutine scope? Well in code, it is represented by an interface called ‘<em>CoroutineScope’</em>. To achieve a cleaner code with the above two mentioned points, we implement this interface and make our custom scope with the same context as <em>viewModelScope</em> but a different dispatcher. This means our custom scope has the same life as the <em>viewModelScope</em>. Here we show the practical usage of mixing a child’s coroutine context with a parent’s content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35a746b663724f0a0d09bc6bc5f75f55/href">https://medium.com/media/35a746b663724f0a0d09bc6bc5f75f55/href</a></iframe><h4>LifecycleScope</h4><p>For lifecycle based components like fragment or activity, we have lifecycle scope.<br>A <strong>LifecycleScope</strong> is defined for each Lifecycle object. Any coroutine launched in this scope is cancelled when the Lifecycle is destroyed. You can access the CoroutineScope of the Lifecycle either via `<em>lifecycle.coroutineScope</em>` or `<em>lifecycleOwner.lifecycleScope</em>` properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ebbd066adecf3a0065d842281a0497/href">https://medium.com/media/63ebbd066adecf3a0065d842281a0497/href</a></iframe><h3>Coroutine cancellation</h3><p>You can cancel a job if it’s taking too long or the requested operation isn’t required anymore, or for fun. To understand cancellation cases clearly, let’s consider we have a scope in which we start a parent coroutine. Inside it we start a child coroutine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/423272342ea439d202d33b86faa2213f/href">https://medium.com/media/423272342ea439d202d33b86faa2213f/href</a></iframe><h4>Parent job is cancelled</h4><p>When a parent job is cancelled, it cancels all it’s child jobs as well. This shows that they imitate the OS world parent-child process relationship.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e19e7df611a649f2c7dfaadf5baff67/href">https://medium.com/media/8e19e7df611a649f2c7dfaadf5baff67/href</a></iframe><h4>Child job is cancelled</h4><p>When a parent job cancels it’s child. It is expected that the child will stop while the parent will continue executing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e963bba6b7d56e580eadba5d62463ddc/href">https://medium.com/media/e963bba6b7d56e580eadba5d62463ddc/href</a></iframe><h4>Child job co-operation</h4><p>But what if the child was doing some kind of a loop.<br>Since we are launching our child coroutine using launch, it won’t block the parent coroutine and will execute on another thread from the Dispatchers.IO it inherits from it’s parent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44be32eefecbaa968361ac4bc1482263/href">https://medium.com/media/44be32eefecbaa968361ac4bc1482263/href</a></iframe><p>What happened here is that the child job didn’t check if it was cancelled and kept executing. Then why did it work previously? Because of the delay(500) provided by the coroutines library.</p><p>Since the framework is built with the following thought in mind -<br>“If we cancel a job (either via cancelling the child job or cancelling the parent job), we want it to stop executing” — Any suspend f() in the coroutine library checks that it the job <em>isActive</em> before executing.</p><p>So in the previous example when delay(500) got over, it checked whether the job it was executing for was alive before continuing. To fix this there are two solutions: Using <em>isActive</em> or <em>yeild</em>. I like <em>isActive</em> better.</p><p>If the job is cancelled, the <em>isActive</em> flag is made false.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28d4b47ddad482aec8771d81ce16d2d/href">https://medium.com/media/f28d4b47ddad482aec8771d81ce16d2d/href</a></iframe><p><strong>Lesson learned:</strong><br>Child jobs should be co-operative enough to notice if they are cancelled, then they don’t execute unnecessarily.</p><h4>Scope is cancelled</h4><p>When we cancel a scope (either a custom scope or one tied to a lifecycle e.g. viewModelScope getting cancelled due view model onCleared being called), all the coroutines running inside the scope are instantly cancelled as well.</p><p>In other words, any work going on in any suspend f() in this scope is stopped. This is only gaurenteed for the coroutines in this scope.</p><p>E.g. if we use the <em>viewModelScope</em> to launch coroutines in repository and cache layer, and while they are ongoing, the scope is cancelled, the coroutines or the suspend f() calls in repository and cache layer are stopped, given that they were running in the same scope. This way we are always ensured we aren’t doing tasks that are no longer required and thus freeing up resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dbea90249eab0bdc1a6c367f083a8b4/href">https://medium.com/media/7dbea90249eab0bdc1a6c367f083a8b4/href</a></iframe><h4>Handling resources</h4><p>There are cases where we’ll need to handle closing resources when our job is cancelled. For this use a try finally block. Coroutine will invoke the finally block in case of cancellation too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/165e26d14f036665fa94b1103bef2ba8/href">https://medium.com/media/165e26d14f036665fa94b1103bef2ba8/href</a></iframe><h3>Timeout handling</h3><p>Do it in a 1000 microseconds or move on. We’ve seen such requirements at some point. These are timeout cases where we want to cancel a job if it’s taking too much time. There is a neat little way to do it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b3f54ede38397aa90b8df7018348f51/href">https://medium.com/media/3b3f54ede38397aa90b8df7018348f51/href</a></iframe><h3>Switching context</h3><p>I hate to do context switching in real life. Not in coroutines.</p><p>Sometimes while doing a task, we may need to do some IO operation, then some DB operation or some kind of computation, and then end with showing some UI on main thread. This require us to jump between correct dispatchers.</p><p>To do this coroutines provide us ‘<strong><em>withContext()</em></strong><em>’</em> operator. Using this we can switch to a different dispatcher and then come back to the old dispatcher as it’s block ends.<br>Remember, calling <em>withContext</em> will suspend the calling f() until the withContext block doesn’t end.<br>i.e. the f() execution won’t proceed until withContext is done executing. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddc04499824865e609c5319cf8ef61b1/href">https://medium.com/media/ddc04499824865e609c5319cf8ef61b1/href</a></iframe><h3>Next part</h3><p>In the next <a href="https://chaddhag.medium.com/practical-concepts-for-coroutines-part-2-709cc6061662">part</a>, we cover converting callback to coroutines, custom coroutine scope, supervisor job and scope, exception handling, structured concurrency and integration with retrofit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95488d2b951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines Fundamentals]]></title>
            <link>https://chaddhag.medium.com/kotlin-coroutines-fundamentals-9aff1e1898bc?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aff1e1898bc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 14:02:31 GMT</pubDate>
            <atom:updated>2021-02-02T04:21:25.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9O172uifC98BfC_wuZ-vQ.jpeg" /></figure><p><em>Originally published at </em><a href="https://www.chaddha.me/kotlin-coroutines-fundamentals/">https://www.chaddha.me/kotlin-coroutines-fundamentals</a> <em>on Dec 23, 2020.</em></p><p>The article covers why we need coroutines, it’s fundamental blocks in theory, and then shows them in action (code) to explain the blocks clearly.</p><p><strong>Kotlin</strong> introduced <strong>Coroutines</strong> for asynchronous programming and more. This article covers why we need Kotlin Coroutines, it’s fundamental building blocks in theory, and then shows them in action (code) to explain the blocks clearly.</p><p>The code shown is available on <a href="https://github.com/GauravChaddha1996/DeepDiveIntoCoroutine">Github</a> as well.</p><h3>Table of content</h3><ol><li>Why do we need coroutines?</li><li>Basic keywords and building blocks<br>2.1 Dispatcher<br>2.2 Coroutine job<br>2.3 Coroutine start<br>2.4 Coroutine context<br>2.5 Coroutine scope<br>2.6 Coroutine builders<br>2.7 suspend keyword<br>2.8 delay keyword</li><li>Enough talk — Show me the code</li><li>Further reading</li></ol><h3>Why do we need coroutines?</h3><p>Apps perform various tasks. For each of this task, operation time varies. While doing these time varying tasks, we need to ensure user experience isn’t degraded. One way to do that (while also reducing bottlenecks) is to do asynchronous operations.</p><p>Let’s discuss potential solutions to do this and their potential problems:</p><ol><li><strong>Threading — </strong>It is a great solution. But managing them can quickly get out of hand.</li><li><strong>Callbacks — </strong>Simple, obvious and easy to implement but can quickly degrades down to callback hell.</li><li><strong>Futures and promises — </strong>Personally I haven’t used them a lot, but I find them not powerful enough for my use-cases.</li><li><strong>Reactive (Rx) streams — </strong>Powerful solution but introduces drastic change in way of thinking.</li><li><strong>Coroutines — </strong>Elegant solution. Offers a small learning curve in comparison to other solutions, minimal change to code and looks the same as synchronous code.</li></ol><p>Let’s begin our understanding of coroutines.</p><blockquote><strong><em>Coroutines are suspendible execution blocks</em></strong></blockquote><p>Don’t worry. I’ll explain these keywords later. In simple words — they are <em>lightweight threads</em> so you can create millions of them and they will run and execute on a shared pool of threads easily.</p><p><strong>Note</strong>: They aren’t bundled with the Kotlin langauge but is instead packaged as a library by Jetbrains. So from here on when I say library, I mean the coroutine library.</p><h3>Basic keywords and building blocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mfz2Etxby5cg0_3MVrGXPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glen Carrie</a> on <a href="https://unsplash.com/s/photos/lego?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The best way to explain all the required keywords is through an example. So let’s take one. Suppose we have a task <strong>T</strong> in which we need to combine values from 5 other long running child tasks — <strong>T1</strong>, <strong>T2</strong>, <strong>T3</strong>, <strong>T4</strong>, <strong>T5</strong>.</p><p>T is a fire and forget kind of task — the invoking page doesn’t care about it’s result and the task must be completed even if the page closes. T1, T2, T3 are network calls, T2 depends on T1 and T3 on T2. T4 is a file read and T5 is a database entry operation which depends on T4. We’ll call the coroutine used to do the task T as <strong>C</strong> and <strong>C1</strong>, <strong>C2</strong>, <strong>C3</strong>, <strong>C4</strong>, <strong>C5</strong> for child tasks respectively.</p><p>Now before we dive into the code, we need to learn a little bit of the keywords and building blocks, otherwise the code can get a little overwhelming. So let’s go over them quickly once and we’ll re-cover this in the code again.</p><p>To understand the following clearly, remember:<br>1. Coroutines are like light-weight threads mapped to actual threads being executed. <br>2. Coroutines can launch other child coroutines and wait on their results.</p><h4>Dispatcher</h4><ul><li>Encapsulates the thread or the thread pool on which coroutine will execute.</li><li>For e.g. For coroutine C, we want it start on a background thread dedicated to IO operations. For C5 we’ll want a DB thread.</li><li>Some dispatchers are already provided by the coroutine library: <br><strong>Main</strong> (thread) , <strong>IO</strong> (thread pool) , <strong>Default</strong> (thread pool) etc.</li><li>We can make out own dispatcher by wrapping a single thread or thread pool.</li></ul><h4>Coroutine job</h4><ul><li>Represents a single coroutine task e.g. C or C1 etc.</li><li>It has a lifecycle with states (Imitating thread states)</li><li><em>States</em> : New, Active, Completing, Cancelling, Cancelled, Completed</li><li>Any parent job like will only complete if all it’s child jobs are completed (or cancelled).</li><li>C can only completed or be cancelled if all C1, C2, C3, C4, C5 are completed or cancelled.</li><li>This imitates the parent-child relationship of process in OS world.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*KoY6Irc3HUHwRfOt.png" /></figure><h4>Coroutine start</h4><ul><li>Tells the library whether we want to start the coroutine as soon as we declare or call it or lazily when asked to later.</li></ul><h4>Coroutine context</h4><ul><li>A key value map of stuff most important for a coroutine like it’s dispatcher, the scope it’s running in, it’s start object, it’s job etc.</li><li>When a child coroutine is started inside a parent one, it mixes it’s own context (usually empty coroutine context) with the one of the parent</li><li>For e.g. C5 when launched will mix C’s context with whatever it’s own context is.</li><li>Suppose C was running on Dispatchers.IO but C5 has to run on DB threads. So we’ll pass CustomDispathers.DB to C5 when launching. The libary will mix the contexts and the CustomDispathers.DB will take priority over Dispatchers.IO</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*lWee3uiS21kQtnii.png" /></figure><h4>Coroutine scope</h4><ul><li>Scope in which a coroutine runs (similar to variable scope). When the scope ends, so does the coroutine.</li><li>When a child coroutine is started inside a parent one it inherits parent scope (Unless specified otherwise). It means that when parent coroutine is stopped, so will the child coroutine since it’s scope was that of the parent.</li><li><strong>Global scope</strong> is provided by the library and lives throughout until the app is living. Coroutines launched on global scope run like daemon threads, they can’t stop the app from exiting.</li><li>In android, there are ways to create scope that can be tied to activity, fragment or manual management.</li></ul><h4>Coroutine builders</h4><ul><li>Builders provided by library to build coroutines around coroutine scopes.</li><li><strong>launch</strong>, <strong>async</strong>, <strong>runBlocking</strong> are some of the builders given by library</li><li>They can add their own context to child builders launched inside.</li><li><em>launch</em> is used to do fire and forget things. It returns immediately when called returning the coroutine job.</li><li><em>async</em> also returns immediately and it returns a special kind of job called Deferred which can be cancelled or it’s result can be awaited.</li><li><em>runBlocking</em> is used to run tasks by blocking whichever thread it’s called on until the block completes.</li><li>We’ll look into example soon to understand these builders better.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e48c44af7bbb77a6f28307883ca1494d/href">https://medium.com/media/e48c44af7bbb77a6f28307883ca1494d/href</a></iframe><h4>suspend keyword</h4><ul><li>suspend keyword is applicable to functions.</li><li>suspend means it may suspend the execution of the current coroutine i.e. saving the function stack frame and execute this function now. It doesn’t necessarily mean that the coroutine be changed.</li><li>Let’s take an example:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddf49eaa4b55b805eacf6f8bd69ad77c/href">https://medium.com/media/ddf49eaa4b55b805eacf6f8bd69ad77c/href</a></iframe><p><strong>Explanation:</strong><br>Here as n1() is called inside coroutineX, it’s same as calling a normal f().</p><p>But when n2() is called from coroutineX, since n2() launches coroutineY, the calling coroutine, coroutineX is suspended and the thread it was executing on is returned to it’s Dispatchers.Default. Here the f() stack of coroutineX is saved.</p><p>When n2() returns the result then coroutineX is resumed from the stack and it executes on either the same or a new thread from Dispatchers.Default thread pool.</p><p><strong>Note</strong>: Dispatchers gaurentee that the coroutine will run on a thread from the pool when they resume their suspension but doesn’t guarentee same thread execution. Usually we don’t care but if one has the use case, coroutines do provide ways to share thread local data between execution on different threads on a Dispatcher.</p><h4>delay keyword</h4><ul><li>It is like sleep for threads. It’s a suspend function which suspends the calling coroutine for the time period mentioned</li></ul><h3>Enough talk — Show me the code</h3><p>Here is the solution for the task T using coroutines. The analysis is done in comments in the code.</p><p>We’ll look what task we are doing, the coroutine we are launching, the thread we are on, whether the operation will suspend the calling function, the scope we use, why we choose a particular coroutine builder, coroutine start context item and how jobs are represented and their end points.<br>Alright, let’s see the code.</p><p>Let’s see the f() for T1, T2 and T3 first.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f3467f7684950879e90b6db10c4728/href">https://medium.com/media/51f3467f7684950879e90b6db10c4728/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/875b450f689201072b14ba94893c7299/href">https://medium.com/media/875b450f689201072b14ba94893c7299/href</a></iframe><p>Why async builder was chosen for T5? <br>I’ll explain in the following code but see if you can piece it together as well.</p><p>Now we see how the creation of coroutine <em>C.</em><br>We launch in global scope to keep the example simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab1e65f7ff12f77780c73fff6be3e2ae/href">https://medium.com/media/ab1e65f7ff12f77780c73fff6be3e2ae/href</a></iframe><p>Now we have to do the tasks one by one. Check the code comments below for detailed explanation on what was done and why.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e43e3cfb2b3c825023b1a2bf33cf48/href">https://medium.com/media/58e43e3cfb2b3c825023b1a2bf33cf48/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47300baa01ce5f94bf0f831f1e8eafa0/href">https://medium.com/media/47300baa01ce5f94bf0f831f1e8eafa0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17a3d1d3323d00ec6d6f7dff33bf8d8c/href">https://medium.com/media/17a3d1d3323d00ec6d6f7dff33bf8d8c/href</a></iframe><p>Until now we have started all our tasks inside C. Now we have to combine the result of all tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3117e3cb19cb2c069d561a2cd58fe432/href">https://medium.com/media/3117e3cb19cb2c069d561a2cd58fe432/href</a></iframe><p>Here is the final code for task T</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87daf4acbb6306d25c59ca0e5bda8afc/href">https://medium.com/media/87daf4acbb6306d25c59ca0e5bda8afc/href</a></iframe><p>Here is the main() calling T and waiting for it’s result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ef47633cf727cb0d50cebc1ad332ff7/href">https://medium.com/media/5ef47633cf727cb0d50cebc1ad332ff7/href</a></iframe><p>Running the above code will give you a result matching to the following :</p><pre>Starting C on DefaultDispatcher-worker-1<br>Inside t1() on DefaultDispatcher-worker-1<br>Starting task T2,T3 on DefaultDispatcher-worker-1<br>Starting task T4,T5 on DefaultDispatcher-worker-1<br>Inside Task T2,T3 on DefaultDispatcher-worker-3<br>Inside t2() on DefaultDispatcher-worker-3<br>Going to await result of task T2,T3 and T4,T5<br>Inside t3() on DefaultDispatcher-worker-1<br>Inside Task T4,T5 on DefaultDispatcher-worker-4<br>Inside t4() on DefaultDispatcher-worker-4<br>Inside t5() on pool-1-thread-1<br>The final result is 1_resultT2_resultT3_resultT4_resultT5</pre><p>(Note: Task t4, t5 doesn’t start until we call await on it. Thats because we used lazy coroutine start on it)</p><p>Now you should have an understanding of all the basic keywords and building blocks.</p><p>The line Coroutines are suspendible execution blocks should make sense now. They are execution blocks which might suspend the calling block but won’t block the thread from which they are called.</p><p>The code shown above is available on this github repo: <br><a href="https://github.com/GauravChaddha1996/DeepDiveIntoCoroutine">https://github.com/GauravChaddha1996/DeepDiveIntoCoroutine</a></p><h3>Further reading</h3><p>I’ve written posts on practical concepts for coroutines where I cover the concepts needed to use coroutines in actual projects, different use-cases that arise, whie showing the code in action to explain the concepts clearly.</p><ol><li><a href="https://chaddhag.medium.com/practical-concepts-for-coroutines-part-1-95488d2b951">Practical concepts for Coroutines (Part 1)</a></li><li><a href="https://chaddhag.medium.com/practical-concepts-for-coroutines-part-2-709cc6061662">Practical concepts for Coroutines (Part 2)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aff1e1898bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical guide to Dagger 2]]></title>
            <link>https://medium.com/android-news/practical-guide-to-dagger-76398948a2ea?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/76398948a2ea</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 11:50:17 GMT</pubDate>
            <atom:updated>2018-09-09T12:32:23.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0QMqRIRO-i8MhdqbSL7Tg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/1WQ5RZuH9xo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pascal Debrunner</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This was originally published at my personal <a href="https://gaurav.chaddha.me/dagger2">blog</a>.</p><p>There are plenty of guides around about using <strong>Dagger </strong>for <strong>Dependency Injection </strong>on Android. They explain what it is, why it is needed, but miss on explaining how to practically do it. Practically using dagger had eluded me for a long time.</p><p>Recently I had my <em>aha </em>moment on how I can use it practically. This success owes a lot to this <a href="https://medium.com/@Zhuinden/that-missing-guide-how-to-use-dagger2-ef116fbea97">article</a> by <a href="https://medium.com/@Zhuinden?source=post_header_lockup">Gabor Varadi</a>.</p><p>This article will cover how to use dagger 2 in a simple situation. If you are looking for advanced usage with scopes and other stuff, this isn’t what you are looking for.</p><p>Let’s get started!</p><h4><strong>Understand the problem</strong></h4><p>Before understanding the problem, lets see where this problem comes from. We want to implement a concept called <em>Dependency Injection</em>. It says that <em>if a component depends on another component, instead of making this dependency itself, it should be provided (injected) from the outside</em>. This will help us in loose coupling between the components, a simple way to test the behavior of a component and much cleaner code. A basic example code is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf081d8f1a88c5c7abf9eb857dc6ad72/href">https://medium.com/media/cf081d8f1a88c5c7abf9eb857dc6ad72/href</a></iframe><p>Here the class <em>A</em> has a dependency on class <em>B</em>. <em>B</em> is supplied to its constructor. This is dependency injection. Let’s take an example from the android world.</p><p>Suppose you have implemented MVP or MVVM pattern. Your presenter (or ViewModel) depends on a database which requires (Application) context in it’s constructor. Since you shouldn’t send android specific stuff to presenter, your view, the activity will end up instantiating the database. The code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd82abcbc0317d26fb930f4a0830cf24/href">https://medium.com/media/cd82abcbc0317d26fb930f4a0830cf24/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e60a745f01eb69b988dac507622261d3/href">https://medium.com/media/e60a745f01eb69b988dac507622261d3/href</a></iframe><p>Now, that seems wrong. Why would the view care about the database. Wouldn’t it be better if presenter took care of that itself? This is our problem — that the view knew about something it shouldn’t, making the involved components tightly coupled.</p><p>This is one of the <em>good reasons </em>to use Dagger 2 for dependency injection. If the dependency was injected to the presenter without view’s intervention, the code becomes more <em>modular </em>and <em>loosely connected </em>which helps in easily changing one component without affecting another.</p><p>Now that you can see where the problem lies, let’s try to understand how to use dagger, and then we will solve this problem.</p><h4>Understanding Dagger</h4><p>First we need to include dagger in build.gradle. This is configuration I have used as of July 2018 (Replace the version 2.16 with whatever is the latest version).</p><p>To include in an android module, add this in the module’s build.gradle :</p><pre>dependencies {<br>    annotationProcessor com.google.dagger:dagger-compiler:2.16<br>    implementation com.google.dagger:dagger:2.16<br>}</pre><p>And for a java module, add this in it’s build.gradle</p><pre>// this is for using apt for annotation processor<br>plugins {<br>    id &quot;net.ltgt.apt&quot; version &quot;0.10&quot;<br>}<br>dependencies {<br>    apt com.google.dagger:dagger-compiler:2.16<br>    implementation com.google.dagger:dagger:2.16<br>}</pre><p>Dagger works via annotations to understand what you want to inject and what the dependencies of a component are. Some basic annotations are:</p><ul><li><strong>@Inject</strong> <br>This annotation is used in 2 ways:<br><strong>1.</strong> By a component to declare it wants these dependencies <br><strong>2.</strong> Telling dagger to use this constructor to make the object if you want to inject this as a dependency. This injection is recursive, i.e. if the constructor has parameters, dagger will look for ways to inject them as well.<br> <br>Let’s take an example to clear that statement. <em>MyClass</em> asks d<em>agger</em> to inject A (Usage 1). Dagger tries to inject A via it’s constructor call (Usage 2) that leads to B’s constructor (Recursive injection — Usage 2). Note that for this to happen, we have marked B’s constructor with @Inject annotation. This will happen until the dependency has a no parameter constructor or until it was already present with dagger somehow (Somebody else created it before you).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa44bb2722dc5631676514d45283af6/href">https://medium.com/media/8fa44bb2722dc5631676514d45283af6/href</a></iframe><ul><li><strong>@Provides and @Module<br></strong>Now you are wondering, what about cases where there are no constructor, like Retrofit client as it is built by its builder. Or when we can’t instantiate the dependency, like a context object. We can’t use @Inject for such cases. Dagger has a solution for such case.<br> <br>There are two annotations for such cases. First is @Provides. Marking a method with this annotation tells dagger, that this method <em>provides the return data type</em>. Let’s take an example to clear that hard statement. Suppose we have a function called getContext() which returns Context object. If I mark this method with @Provides, dagger now knows where to find the context (Since it’s the return type of our method).<br> <br>But wait, what if I need to inject ApplicationContext and ActivityContext as dependency somewhere. For both the return type would be Context. Well, dagger provides a @Named annotation to mark an Id for your @Provides methods. So for application context we would use something like @Named(“ApplicationContext”) and similarly for ActivityContext. You can find the example in the code below. <br> <br>But where do I define this @Provides methods? <br>The answer is @Module. It is used on a class to grouping of similar types of @Provides methods together. For example a class named ContextModule marked with @Module will have @Provides methods for ApplicationContext and ActivityContext. These methods will use @Named to differentiate between the same return type. Also, remember that you need to specify the name or id when asking for your dependency if you have used it when we provide the dependency. Example: Context is marked with name “ApplicationContext” in MyDatabase code below. In this way dagger knows to inject the dependency marked with this name.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ddfe9e8d94ff63decf13067f2387828/href">https://medium.com/media/8ddfe9e8d94ff63decf13067f2387828/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31836f39d4d4152bc254fd1c798d3a7a/href">https://medium.com/media/31836f39d4d4152bc254fd1c798d3a7a/href</a></iframe><p>As you can see, the module asks for the context it has to provide in it’s constructor. If there is any component like Context or ContentResolver that we can’t instantiate or even build like Retrofit, we ask for them in the module’s constructor. And then via it’s @Provides methods the module will tell Dagger what it can provide.</p><ul><li><strong>@ Component</strong><br>We have seen the ways we can ask and provide dependencies. Now we need a way to define the component which connects those annotations i.e. will inject those dependencies wherever needed. So logically, we need to tell it the modules to use and the consumers, the one’s who needs these dependencies. @Component automatically picks up @Inject constructor calls. We’ll see the code in the coming examples.</li></ul><h4>Solving the problem</h4><p>Remember our problem — the view was instantiating the database and then passing it to the presenter.</p><p>First we look at the MyDatabase class. We already saw how we marked it’s constructor as @Inject. This tells Dagger to use this constructor to inject this whenever MyDatabase is needed as a dependency. It also tells dagger that my constructor parameter that I depend on, is named “ApplicationContext”. Then we used a ContextModule to provide that “ApplicationContext” named dependency.<br> <br>Now, we will define the component. We need to tell it what modules to use, and where it would need to inject. Since we need to inject the MyDatabase to MyPresenter, we only need to tell Dagger about the ContextModule (Since component will pick up @Inject on MyDatabase constructor directly). To tell it where we need to inject, we define a function called inject that returns void and takes the consumer as a parameter. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/630483ddbf55f376cb643de0c804ff42/href">https://medium.com/media/630483ddbf55f376cb643de0c804ff42/href</a></iframe><p>But this is just an interface. Where is the code that will actually inject?</p><p>Build the project once. Dagger generates all the code that is required to inject dependencies at compile time. After the build, DaggerMyComponent class is created which implements the MyComponent interface. Dagger generates this implementation with a Dagger prefix in the name. This implementation has methods to provide dependencies and inject them to our consumer (Both of which we defined in the interface).</p><p>Now we need a way to provide this component to the consumers. In most cases the dependencies we want to inject can be created on an application scope, hence we declare the component as a static variable in the Application class. Next we need to build it using the builder function in the DaggerMyComponent class. The builder of the components only asks for the modules it depends on. Finally, we make a function to return the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52eebec063e2c0ff69213a3cca080e77/href">https://medium.com/media/52eebec063e2c0ff69213a3cca080e77/href</a></iframe><p>Now here is the presenter asking for dependencies to be injected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b07a1c21f4d2c839ca87f4f883bf28e/href">https://medium.com/media/7b07a1c21f4d2c839ca87f4f883bf28e/href</a></iframe><p>That’s it. We have declared where we would provide our dependencies, and how consumers can ask for them.</p><h4>Bonus 1 — Injecting interfaces instead of implementations</h4><p>There is one more thing you should know. Suppose MyDatabase was implementing an interface. Let’s call it Database. Instead of directly injecting the implementation, we want to inject the interface instead. For this, first we need to make a module which takes an implementation as it’s constructor parameter. Then in the ‘provides’ method, it returns the implementation object(MyDatabase), but the return type is of the interface (Database). Thus effectively when we inject the interface, it will be a reference to an actual implementation. Then we need to include this module in our component, and inject the interface directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d02bb6f31c512ced502492c37d863e0d/href">https://medium.com/media/d02bb6f31c512ced502492c37d863e0d/href</a></iframe><h4>Bonus 2 — Singleton</h4><p>Yeah, Singleton. We all have been in situations where we needed to make a dependency a singleton class, e.g. Database, or maybe a state manager of some sorts etc. There are two rules:</p><ol><li>If you are injecting the dependency via @Inject on the constructor of the dependency, just mark the class as @Singleton.</li><li>If you are using @Provides in a module, just mark the method as @Singleton.</li></ol><p>Dagger will make sure that for the given scope, that is application scope in our simple example, the dependency remains a Singleton.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3753333a902dd6f269e801c54f214190/href">https://medium.com/media/3753333a902dd6f269e801c54f214190/href</a></iframe><h4>Summary</h4><p>In summary, the rules for using Dagger for Dependency Injection are</p><ol><li>Use @Inject on constructors wherever you can.</li><li>Make modules for stuff you can’t instantiate directly (e.g. Retrofit client as it’s built by it’s builder) or for stuff you can’t create like Context.</li><li>Also make ‘provides’ method in modules if you want to inject interfaces instead of implementations.</li><li>Use @Singleton if you want the dependencies to remain a Singleton.</li><li>Include all the required modules in the component and define where that component will inject dependencies to.</li><li>Use @Inject to ask dagger to inject dependencies you have declared.</li></ol><h4>Further reading</h4><ol><li><a href="https://blog.mindorks.com/introduction-to-dagger-2-using-dependency-injection-in-android-part-1-223289c2a01b#.4cae8wf66">Introduction to Dagger 2, Using Dependency Injection in Android: Part 1</a></li><li><a href="https://blog.mindorks.com/introduction-to-dagger-2-using-dependency-injection-in-android-part-2-b55857911bcd">Introduction to Dagger 2, Using Dependency Injection in Android: Part 2</a></li><li><a href="https://blog.mindorks.com/android-dagger2-critical-things-to-know-before-you-implement-275663aecc3e#.crrgqwnbi">Android Dagger2: Critical things to know before you implement</a></li><li><a href="https://fernandocejas.com/2015/04/11/tasting-dagger-2-on-android/">Tasting Dagger 2 on Android</a></li><li><a href="http://konmik.com/post/snorkeling_with_dagger_2/">Snorkeling with Dagger 2</a></li><li><a href="http://frogermcs.github.io/inject-everything-viewholder-and-dagger-2-example/">Inject everything — ViewHolder and Dagger 2 (with Multibinding and AutoFactory example)</a></li></ol><p>I hope this article helped you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76398948a2ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/practical-guide-to-dagger-76398948a2ea">Practical guide to Dagger 2</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning android development]]></title>
            <link>https://medium.com/android-news/learning-android-development-e2d4d239a7a3?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2d4d239a7a3</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Mon, 26 Feb 2018 15:08:36 GMT</pubDate>
            <atom:updated>2018-03-02T19:07:40.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*FNfuObSMRmCB1wP1QKMDEQ.png" /></figure><p>This post is meant for people looking to start android development, and also for people who have covered the basics and now are looking to improve themselves. I would be providing resources I came across while learning android development.</p><h3>Getting started with android development</h3><ul><li><strong>Learning pre-requisites skills</strong></li></ul><p>I think that one should learn a a bit of Java language before going into android development. You can take a course on Udacity, or watch Youtube videos or a book. I learned it from two sources: TheNewBoston Youtube video playlist of “Java (Beginner) Programming Tutorials” (Tip: Don’t install Eclipse. Go for IntelliJ IDEA) and a book called “Java: A Beginner’s Guide” by Herbert Schildt.</p><p>I would recommend to install Ubuntu or any other Linux distro as Android studio, the IDE used to develop android apps is painfully slow on Windows if you don’t have a SSD. This will help you learn Linux. Also if you have the time, do a course or watch videos on Git to learn it’s basics. Learning git would definitely benefit you.</p><ul><li><strong>Learning the basics</strong></li></ul><p>Now that you know the pre-requisites, we can move to learn the basics of android development. I would recommend using either of the resources (Do some research to find which one suites you best)</p><p>1. <a href="https://developers.google.com/training/">Google Developers Training</a><br>2. <a href="https://www.udacity.com/google">Udacity-Google Partnership</a><br>3. <a href="https://developer.android.com/index.html">Getting started — Android Developers </a><br>4. (I learned from this) <a href="https://www.youtube.com/playlist?list=PL6gx4Cwl9DGBsvRxJJOzG4r4k_zLKrnxl">Android App Development for Beginners by TheNewBoston</a></p><p><em>Although TheNewBoston videos are pretty good, I would recommend to use the other resources as they are from Google themselves.</em></p><p>After you have learned the basics about android development, you should be comfortable in using Android Studio IDE, logcat, debugger, and should know about Activity lifecycle, Fragments, Screen navigation, View Pager, Notifications, RecyclerView, SharedPreferences, Context, Dialogs, Basic threading, Services etc.</p><h3>Improving your skills</h3><p>Next to improve your skills, I would recommend to learn the following things one by one or as the need arises (Keep in mind that this list isn’t a complete guide — it is merely what I felt from my experience is important, and learning them will take a long time) :</p><ul><li>MVP architecture, MVVM architecture, Android code style and guidelines, Material design, Design support library, Basic animations, Constraint layout.</li><li>3rd party libraries like ButterKnife, Glide, Picasso, Timber.</li><li>Networking using OkHttp, Gson, Volley, Retrofit or any other.</li><li>Database and ORM’s. Example: Room, SQLlite, Realm, ORMLite, greenDOA etc.</li><li>Custom views and Loaders.</li><li>Design Patterns, Testing, FindBugs, PMD, Functional Programming concepts, Firebase, RxJava, RxAndroid, Dagger, SOLID Principles. (These are pretty advanced so try not to jump to these. Take your time.)</li></ul><h3>Resources</h3><p>The best resource I have come across learning, better than even courses is blog posts. Most of what I’ve learned is from reading blogs and then implementing it.</p><ul><li>Great publications about android development on Medium: <a href="https://android.jlelse.eu/">AndroidPub</a>, <a href="https://mindorks.com/">Mindorks</a>, <a href="https://medium.com/google-developer-experts">Google Developer Experts</a>, <a href="https://labs.ribot.co.uk/">Ribot Labs</a>, <a href="https://medium.engineering/">Medium Engineering</a>, <a href="https://medium.freecodecamp.org/">FreeCodeCamp</a>, <a href="https://hackernoon.com/">Hackernoon</a>, <a href="https://medium.com/upday-devs">Upday Devs</a>, <a href="https://proandroiddev.com/">ProAndroidDev</a>, <a href="https://medium.com/lateral-view">Lateral View</a>, <a href="https://medium.com/fueled-android">Fueled Android</a>, <a href="https://blog.aritraroy.in/">Aritra Musings</a>, <a href="https://lorentzos.com/">Dionysis’ Lorentzos blog</a>, <a href="https://medium.com/google-developers">Google Developers</a>, <a href="https://medium.com/inloop">Inloop</a>, <a href="https://medium.com/android-circle">Android Circle</a>, <a href="https://medium.com/exploring-android">Exploring Android</a> etc.</li><li><a href="https://codelabs.developers.google.com/">Google Developer Codelabs</a></li><li>Follow the people who write in these publications here and on twitter to get updates about what they post. This is a good way to keep up with what is new and to improve yourself.</li><li>Subscribe to newsletters to get curated lists of good posts and news: <a href="http://androidweekly.net/">Android Weekly</a>, <a href="https://www.androiddevdigest.com/">Android Dev Digest</a>, <a href="https://infinum.co/our-stuff">Infinum Android team</a>, <a href="https://android.jlelse.eu/">Android Pub newsletter</a> etc.</li><li>Regularly visit the subreddit <a href="https://www.reddit.com/r/androiddev/">/r/androiddev</a> to get updates and news about android development.</li><li>Make a Twitter account and follow some android developers. I wrote a <a href="https://www.reddit.com/r/androiddev/comments/6cawdz/which_android_developers_do_you_follow/dhvoayc/?context=0">comment</a> on reddit about some android developers one can follow.</li></ul><h3>Tips for software development</h3><ul><li>Care about code quality — read about modularity, seperation of concern, MVP, MVC, MVVM, function length, class size, variable name etc. Apply the good practices you read about this stuff.</li><li>Development takes time. You will first need to learn basic syntax and some basic components before jumping in.</li><li>Slowly increase the projects complexity per each 2–3 projects. Learn new things and apply them.</li><li>Wisely choose what tech or library or framework you use, and read the docs first. Google the problem instead of asking somebody first. Try every stack overflow possible, you will learn the ways of “not doing” a task, which is very important.</li><li>If you feel the need to diversify yourself — Read <a href="https://github.com/shekhargulati/52-technologies-in-2016">Shekhar Gulati 52 Technologies</a> in 2016.</li></ul><p>You can also refer to this awesome <a href="https://blog.mindorks.com/how-to-learn-android-development-f33dd6dba40d">guide</a> from <strong>Mindorks</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2d4d239a7a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/learning-android-development-e2d4d239a7a3">Learning android development</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey to the world of MVP and Loaders ( Part 2)]]></title>
            <link>https://medium.com/mindorks/a-journey-to-the-world-of-mvp-and-loaders-part-2-e176200e5866?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/e176200e5866</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Mon, 26 Jun 2017 04:49:50 GMT</pubDate>
            <atom:updated>2017-06-26T05:02:38.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0OCYX9hk5FKwojd266pCw.png" /></figure><p>In this post, we will focus on the <a href="https://developer.android.com/guide/components/loaders.html"><strong>Loader API</strong></a>. If you do not know about <em>MVP</em> pattern, I’ll suggest you to read the <a href="https://medium.com/@Batdroid/a-journey-to-the-world-of-mvp-and-loaders-part-1-1a6bffb651b5">Part 1</a> before this.</p><p>Example project for this post is at this <a href="https://github.com/GauravChaddha1996/MVP-Loader-Example">link</a>. The <em>master</em> branch explores both <em>MVP</em> and <em>Loader</em> API while the other <em>only-mvp</em> branch only explores <em>MVP</em> as explained in Part 1.</p><p><strong>Loader API and the rotation problem<br></strong>The rotation problem is that we fetched some data by a costly operation like a network call or a complex query with transformation from a database. Then the user rotated the phone and we don’t want to do the costly query again. Here comes in the Loader API. Loader API was introduced in API level 11 and is used to load data from a data source to display in an activity or fragment. It has many advantages and solves many problems but the most useful one to us regarding rotation is that Loaders are managed by the system and they persist during configuration changes. According to the documentation of Loaders:</p><blockquote>Loaders persist and cache results across configuration changes to prevent duplicate queries.</blockquote><p>So if we make the loader load presenter in the first creation of our activity, and then rotate the phone which will recreate the whole activity, we will not make a duplicate query and get back the same presenter as pre-rotation. And then using the cached data in the presenter we can persist our state or instance of data across rotation. Now lets dive into the code.</p><p>Loader API has three major classes and interfaces:<br>1. <a href="https://developer.android.com/reference/android/app/LoaderManager.html"><strong><em>LoaderManager</em></strong></a>: Responsible for managing loaders for an activity or fragment. The system automatically determines whether a loader with the same integer ID already exists and will either create a new loader or reuse an existing loader. So in case of rotation, it reuses the same loader giving us our pre-rotation presenter object back.</p><p>2. <a href="https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html"><strong><em>LoaderCallbacks</em></strong></a>: Interface required to be implemented by the activity or fragment to get the callback from when loader events occur. Although there are three functions, we mostly need to focus on two for our rotation case.</p><ol><li><strong>onCreateLoader(int, Bundle)</strong>: Callback for when the system needs a new Loader and thus is asking for us to create one.</li><li><strong>onLoadFinished(Loader&lt;D&gt;, D)</strong>: Callback for when the load has been finished by the loader and we get back the data as ‘D’.</li><li><strong>onLoaderReset</strong>: Callback for when a previously created loader is being reset. We won’t need to focus on this though for our rotation use case.</li></ol><p>3. <a href="https://developer.android.com/reference/android/content/Loader.html"><strong><em>Loader</em></strong></a>: This is the abstract class which serves as the basis for all loader classes.</p><h4><strong>Implementation of loader API</strong></h4><p>Lets start with defining our custom loader class. So we need to extend the abstract Loader class. We will have a private member, our presenter we want to load, and will override one function: onStartLoading(). It is normally called as soon as our activity or fragment gets started. As our result doesn’t take time to load and is created when the loader was being created, we will deliver it as soon as this function is called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cdfd25eb63510a5e45299584cf8e9f1/href">https://medium.com/media/5cdfd25eb63510a5e45299584cf8e9f1/href</a></iframe><p>In our activity, we will start the initialization of the Loader in onCreate(). If this is the first time activity is being created a new loader will be created by the system by calling onCreateLoader() callback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea0f5ad10145a4ed2615f45c2bdf385/href">https://medium.com/media/eea0f5ad10145a4ed2615f45c2bdf385/href</a></iframe><p>And the loader callbacks are implemented in an activity or fragment as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba4fe5671b54abe454215e555d693b6/href">https://medium.com/media/0ba4fe5671b54abe454215e555d693b6/href</a></iframe><p>In this way we can persist our presenter during rotation, in turn persisting our data and any kind of database or network request we were making.</p><p>Please note that there are many alternatives to Loader API to persist presenters and many other uses of Loader API. The documentation on Loader API is pretty good, also for more understanding you can read this gold <a href="https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832">article</a> by Ian Lake.</p><p>Please check out the <a href="https://github.com/GauravChaddha1996/MVP-Loader-Example">example project</a> for full code implementation.</p><p>And I would love to discuss your thoughts on this. If you like the article, hit that green heart button.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e176200e5866" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/a-journey-to-the-world-of-mvp-and-loaders-part-2-e176200e5866">A journey to the world of MVP and Loaders ( Part 2)</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey to the world of MVP and Loaders ( Part 1)]]></title>
            <link>https://medium.com/mindorks/a-journey-to-the-world-of-mvp-and-loaders-part-1-1a6bffb651b5?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a6bffb651b5</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Mon, 26 Jun 2017 04:44:04 GMT</pubDate>
            <atom:updated>2017-07-03T10:57:55.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61Zu45jwt1PLUxquTUOpbQ.png" /></figure><p>This post will be split into two parts. The first part explains the need, the job of each component of <em>MVP</em> and then the actual code to make your project organized in <strong><em>Model-View-Presenter(MVP)</em></strong> pattern. While the second part will focus on <a href="https://developer.android.com/guide/components/loaders.html"><strong><em>Loader API</em></strong></a>, on how to use it to save your presenters during rotation.</p><p>The example project for this post is at this <a href="https://github.com/GauravChaddha1996/MVP-Loader-Example/tree/only-mvp">link</a>.</p><p>The <em>only-mvp</em> branch of the example project deals with <em>MVP</em> only. The <em>master</em> branch shows an example of <em>MVP</em> and <em>Loader API.</em> We will cover the <em>master</em> branch in the second post.</p><h4>Let’s understand the need for MVP.</h4><p>We all started with making small projects and as time went on, the complexity of these projects started to increase, bringing in chaos.</p><blockquote>“The Only Thing That Is Constant Is Change -”― <a href="http://www.goodreads.com/author/show/77989.Heraclitus">Heraclitus</a></blockquote><p>And the time to make these changes or new features in our chaotic complex project kept increasing. Also the amount of code which is deleted or shifted or is written new to make these changes kept increasing. And how can we forget about the bugs? Complexity increase brings all kinds of bugs and we first have to locate the bug before we can squash it. But we can’t locate it in that messy code, can we?</p><p>We slowly realize how the mixing of different parts of code led to time being wasted on stupid bugs and how hard it made making changes or adding new things making our project unmaintainable. We slowly also realize our mess has been handling all kind of stuff regarding our view, transformation logic, navigation logic and business logic. We can’t even test any logic or view as all of it is too interdependent.</p><p>We realize that what we don’t have is separation of concern and it is causing us many kind of problem. <strong><em>Separation of concern</em></strong> means that the concern of how data is shown to the user, how it is fetched and what transformation we applied on it should all be separate so we easily change any of them without worrying about affecting the other one.</p><p><strong>This is the need of Model-View-Presenter <em>(MVP)</em> pattern —<em> Separation of concern</em></strong>. Now that we know we need it, we need to understand the job of each component.</p><h4>Job of Model</h4><p><em>This component’s job is to implement the business logic and handling of data. Handling of data refers to the fetching of data( Either from local cache, or from external storage or from server in a network call) and then saving it in memory or cache or external storage.</em></p><p>Let’s take an example to understand it : <br>You have a button in your app and it loads some recipes from the server but only for premium accounts. Now when a user clicks on it, the network request reaches the models which is implementing the business logic, so it first checks with the user data stored if the user has a premium account or not. If the account is not premium, the request is denied and an upgrade dialog is shown. Otherwise, the data is fetched from the server and is saved in the database to be shown instantly the next time. Here is some pseudo code for it for better understanding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab1e7d54b48d263cfc96ae64d9416a8/href">https://medium.com/media/aab1e7d54b48d263cfc96ae64d9416a8/href</a></iframe><h4>Job of View</h4><p><em>This component only job is related to the views that are being displayed. It doesn’t know how they are fetched or even if they are coming from the cache or from a network call. Activity, Fragment etc. components come under this.</em></p><p>Continuing the example, you have a recipe screen where you show the list of recipes or an upgrade dialog. Now this view will have this kind of pseudo code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55198fc0065d9b033ba024c7634ae40e/href">https://medium.com/media/55198fc0065d9b033ba024c7634ae40e/href</a></iframe><h4>Job of Presenter</h4><p><em>This component is the handler of logic and decides when, what and how to display data. It is responsible for getting the UI events, asking the model to make necessary changes, applying transformation and caching results before sending the data back to the view.</em></p><p>In the example we have seen, the user wanted to fetch the recipes and the presenter asked the model to fetch the recipes. This is the first role of presenter — handle UI events and ask model for data. <br>When those recipes results came back, it cached them, and then shipped it to the view. This is the second role of presenter — cache and send data to be displayed to the View.<br>Maybe the user now applied a filter to the recipes. We have already fetched the whole list of recipes. Do we fetch the filtered recipes again? No, we will simply apply a transformation filter on the cached recipes. This is the third role of presenter — transform data if needed. <br>Here is some pseudo code for it :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84e629e885c76139623088e0375f06a3/href">https://medium.com/media/84e629e885c76139623088e0375f06a3/href</a></iframe><h4><strong>Implementation of MVP</strong></h4><p>Now that you understand what is the job of each MVP component, lets dive into how we actually implement it in code.</p><p>Suppose we have a Activity acting as our view. First we make the presenter object in our activity onCreate(). To connect the presenter and the view, we use an interface. The interface defines all the functions that presenter can call on the view and they will all be somehow to update the UI. The interface is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/175c18b65bb3a97cdf28df6e5b654d6e/href">https://medium.com/media/175c18b65bb3a97cdf28df6e5b654d6e/href</a></iframe><p>We implement it in our activity so that presenter can send UI updates to us. We say that we attach the view in onResume() to the presenter, i.e. we pass an interface implementation asking the presenter to give us UI updates on this. And in onPause(), we set it to null as we can’t display UI updates anymore, hence we don’t need UI updates from presenter. The code for the view (in this case an activity is as follows) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bdd37db160250f6d6dfcd9b40f9663d/href">https://medium.com/media/4bdd37db160250f6d6dfcd9b40f9663d/href</a></iframe><p>Presenter will have attachView() and detachView() functiong alongside some other functions to handle UI events from the view. The presenter is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e3b3fc39063b3e62709d45d74d0b63/href">https://medium.com/media/66e3b3fc39063b3e62709d45d74d0b63/href</a></iframe><p>And DataManager is the class which acts as the interface for every presenter to interact with the model. In my opinion it should be kept a singleton. You can use the lazy instantiation method to instantiate it with application context in the application class.</p><pre>//MyApplication.java</pre><pre>//onCreate()<br>DataManager.init(this.getApplicationContext());</pre><p>To access it we can then use the public static method in DataManager called getDataManager() which returns the singleton reference. The Model pseudo code that we saw when understanding the job of Model component will actually be present in DataManager class. It also delegates the tasks to other managers, for example: network requests for model are delegated to NetworkManager, SharedPreference changes to SharedPreferencesHelper etc. It is also responsible for checking that if we have cache data, then update the UI with it while proceeding with network call, and when the network call returns, update the database and cache , and update the UI again. The sample code for the data manager :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65f309b7efd7a2503d542b1ba82a2cc8/href">https://medium.com/media/65f309b7efd7a2503d542b1ba82a2cc8/href</a></iframe><p>Please check out the <a href="https://github.com/GauravChaddha1996/MVP-Loader-Example/tree/only-mvp">example project</a> for full code implementation. The next <a href="https://blog.mindorks.com/a-journey-to-the-world-of-mvp-and-loaders-part-2-e176200e5866">part</a> will cover Loader API and rotation problem.</p><p>And I would love to discuss your thoughts on this. If you like the article, hit that green heart button.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a6bffb651b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/a-journey-to-the-world-of-mvp-and-loaders-part-1-1a6bffb651b5">A journey to the world of MVP and Loaders ( Part 1)</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the enigma of RxJava (Part 1)]]></title>
            <link>https://medium.com/hackernoon/understanding-the-enigma-of-rxjava-part-1-8e04a456d9de?source=rss-449c72129f69------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e04a456d9de</guid>
            <category><![CDATA[frp]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Gaurav Chaddha]]></dc:creator>
            <pubDate>Mon, 03 Oct 2016 07:33:51 GMT</pubDate>
            <atom:updated>2017-07-14T10:46:35.860Z</atom:updated>
            <content:encoded><![CDATA[<p>The first thing that came to my mind when I first heard about<strong> <em>Functional Reactive Programming</em> </strong>(<strong><em>FRP</em></strong>) and <strong><em>RxJava</em></strong> was why?! Why switch from my comfortable Imperative programming and AsyncTask world? The answer was not clear at that time but after recent experiences I felt the need for it. In this part I will try to convince you, honestly myself as well a little bit, to learn <em>RxJava</em> and then we will discuss what it is we are trying to achieve using <em>RxJava</em> (Psst… Hint, it is a paradigm). In later parts, we will cover the basics of <em>RxJava</em> and it’s implementation in real life based android applications.</p><h3>Why should I use RxJava?</h3><p><em>If you are asking this question, good then. Let’s begin!</em><br>I started this project called <a href="https://github.com/GauravChaddha1996/Pokify">Pokify</a>, which was based on Pokémons. In that project I made a simple SQLlite Helper class and used Executor Service for threading and AsyncTask for other asynchronous operations. It was a pain to manage all of these and after numerous incidents of cursing and fixing my stupid bugs, I realized the need of <em>RxJava</em> for my threading and asynchronous operations. Without even a waste of second, I committed myself to <em>RxJava</em> because that is <em>what devs do, they learn new stuff when they aren’t satisfied with what they have on their plate.</em></p><blockquote><em>If you have also cursed AsyncTask, it is time to stop cursing and start moving on.</em></blockquote><p>Oh and I’ve got ample reasons which will be enough to convince you to move on!<br>Here are some <strong><em>advantages</em></strong> of using <em>RxJava</em>:</p><ol><li><strong><em>Avoid the </em></strong><a href="https://www.quora.com/What-is-callback-hell"><strong><em>Callback Hell</em></strong></a><strong><em>.</em></strong><br>If you have ever made nested network calls you know what I’m talking about. It is a very common problem and a dreaded one too, which is easily solved by RxJava.</li><li><strong><em>Threading is a hundred times easier.</em></strong><br>No more worrying of updating the views and getting the dreadful ‘~UI Thread crash’.</li><li><strong><em>Asynchronous operations becomes way easier using RxJava.</em></strong><br>Using AsyncTasks you have a large set of problems. The code is not clean, testing it is a pain, or if you are trying to cache the download of an AsyncTask on rotation of the device, well Good Luck! Also, be it handling of activity life-cycle, or multiple network calls, or even error handling of nested AsyncTasks…I could go on but I guess you see the problem, right? With RxJava all these can be tackled with fairly easily.</li><li><strong><em>UI and View-Handling. </em></strong><br>Ever made a network call when the user searches for something in an EditView? We don’t want to make a network call for every ‘R’ ,‘Rx’, ‘RxJa’ or ‘Rxjava’. We only want to do so when the user has stopped typing for at least 250ms. If you start thinking about the solution with imperative coding, you see the flaw there, right? With RxJava we will solve this pretty easily using the <a href="http://reactivex.io/documentation/operators/debounce.html">debounce</a> operator.<br>Other View-Handling stuff like listening for double tap or triple taps is a piece of cake with RxJava. Listening to EditView text changes is infinite times easier. Want to create multiple listeners for button click? No problemo! With RxJava, you can do it all with many other cool advantages as well.</li><li><strong><em>A standard error handling mechanism.</em></strong><br>Ever made a simple weather app? You have to first fetch the location and then its weather. If using AsyncTasks, it will have nested tasks and a nested error handling mechanism which is not very clean. With RxJava you get a standard way of handling all these errors. Neat, right?</li><li><strong><em>RxJava has a lot, literally, a lot of operators for your use.</em></strong><br> Anything you can think of will most likely have an operator already. That too all tested!</li><li>Using the <em>FRP</em> paradigm (The paradigm whose library is RxJava) you will be able to easily add code or remove it. If you followed FRP correctly, most of the times your structure will tell you where the bug is coming from and then we can squash it!</li></ol><p><strong><em>Have I convinced you yet? Good.</em></strong></p><p>Now let me break the truth to you. The idea that we want to implement using <strong><em>RxJava</em></strong> is actually <strong><em>Functional Reactive Programming(FRP)</em></strong>. It is a paradigm on how we should write our program or project. In fact, it is one of the many others like OOPS paradigm etc. The way to easily follow it in Android is through RxJava, which is an extension library of <a href="http://reactivex.io/">Reactive</a>X for Java that can also be used in android for programming in FRP. FRP paradigm can also be implemented without using RxJava in some places which will get clear in the breakdown of FRP.</p><h3>The Breakdown of Functional Reactive Programming</h3><p>OK, Now that I have you on my side of the table, we are going to break down <em>Functional Reactive Programming</em> to understand clearly all it’s aspects; what it is and how will we implement this in our project using RxJava. It is made of two parts: <strong><em>Functional Programming</em></strong> and<strong><em> Reactive programming</em></strong>.</p><h4>What is Functional Programming?</h4><p>Typically, most of us have an imperative mindset. We see things as objects which bring together two things: data and functions that act on that data. In OOPS paradigm data can be changed or mutated. But in <strong><em>Functional Programming</em></strong> we code the program as such that we try to avoid data mutation. Instead we create a new set of data every time we need to mutate the data. This helps in the way that a function that transforms the data set will always return the same value as the original data set is never mutated. Thus this function is easily unit-testable.</p><h4>Difference Between Imperative and Functional Approach</h4><p>OK, I know, I know, you want an example. Suppose you have a generic thing called Figure. Square, circle, triangle are all Figures.Now you have a box containing 3 squares.You need to convert them all to circles applying some operations. The imperative approach to solve this is iterate through the list and convert each item from a square to a triangle and then to a circle one by one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cfi2TTwXDSfUYErw0GkVAg.jpeg" /><figcaption>Imperative approach to problem: Given a data set( list) of 3 squares convert it to data set of circles using operators.</figcaption></figure><p>However the functional approach differs as such that we put our 3 items in a stream. Then we convert this stream of squares into a stream of triangles and then this stream into a stream of circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky7P2Dt44CFioLE563TT6Q.jpeg" /><figcaption>Functional approach to problem: Given a data set( list) of 3 squares convert it to data set of circles using operators.</figcaption></figure><p>Both of the paradigm are achieving the same result, it is just a matter of how it is done. For Asynchronous and some other operations an imperative approach has many problems and that is why we are switching to a functional approach.</p><h4>Pure functions</h4><p><em>Functional Programming </em>introduces a very cool concept of<strong><em> Pure functions. </em></strong>This blog <a href="http://blog.jenkster.com/2015/12/what-is-functional-programming.html">post</a> explains this beautifully. This is the implementation of FRP without using RxJava and is very powerful. The summary of the post is this;<br>Consider the function:</p><pre>function a()<br>{<br>    item = queue.getItem();<br>    process(item);<br>    print(item.name);<br>}</pre><p>The function has a hidden input: ‘queue.getItem( )’. It is called hidden because looking at the function signature one cannot determine that it is required by the function. This is known as <em>a </em><strong><em>Side cause</em></strong><em>.</em> Similarly it is printing the item name. This also cannot be predicted by the signature and hence is a hidden output called as <strong>Side effect.</strong></p><p>As you can imagine Side effects and Side causes lead to numerous problems and bugs that can’t be easily tracked as they are hidden. They also lead to testing problems.</p><p>Any function which doesn’t have a hidden input or output is known as a Pure function. For pure functions, looking at the function signature, we can determine what it’s inputs and outputs are. Example:</p><pre>function int add ( Integer a, Integer b) <br>{<br>    c = a+b;<br>    return c;<br>}</pre><p><strong><em>Functional Programming</em></strong> is programming using pure functions and removing side effects are much as possible. Functional languages are languages which encourages and provides easy way to do functional programming.</p><h4>When to use Functional Approach?</h4><p>My view is that Functional programming is better to deal with the data of people while OOPS is better when we deal with people. In a MVP pattern the model classes should use the OOP paradigm while the funtions inside these classes should use Functional approach. Transformation or manager classes (Like presenter or views in MVP) should also use pure functions to operate on model objects having pure functions. The benefits of both world! Using functional approach we can gain the advantages listed above.</p><h4>What is Reactive Programming?</h4><p><strong><em>Reactive Programming</em></strong> is the paradigm that says that our code should be as such that we react to changes. A very good explanation of reactive programming is given in this medium <a href="https://edgecoders.com/how-to-explain-reactive-programming-to-a-5-year-old-e802c5385aee#.iqzs91ibd">post</a>. A good example from this post is: Suppose you order a coffee and while waiting you focus shifts and you start reading a medium article. Now as soon as your order comes up and your name is called you react to this change and your focus changes from the article to coffee.This is reactive programming.</p><h4>What is Functional Reactive Programming?</h4><p>A mixture of Functional and Reactive Programming is called <strong><em>Functional Reactive Programming.</em></strong> In this case we code our project as such that we react to changes using the functional paradigm. A very good resource for understanding FRP is this <a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754">gist</a> by Andre Stalz. To understand FRP lets see the mixing of Functional Programming and Reactive Programming using an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RwiqAB-9LUAlEDGrZYOVg.jpeg" /><figcaption>Button click stream example for FRP</figcaption></figure><p>Suppose we have to listen for double or more taps on a button. We can see in the marble diagram that we first have the event stream of user clicking the button. This event stream is a functional programming data set. First we use <em>RxJava</em>’s operator called buffer and throttle the click stream.This operator will merge/accumulate all the events for the given parameter time (250ms) and adds them as one. To make it very clear in terms of <em>FRP</em>, we used pure functions from <em>RxJava</em> to have a new data set which has mutated from the original one. Next we map these click events as number of clicks to the data set. Again we have a new mutated data set which we have created using <em>RxJava</em>’s functional approach . Then we filter our data set for items greater than or equal to 2. Now we react to these clicks data set using the reactive paradigm.<br>To summarize this example, we used pure function operators of <em>RxJava</em> to mutate our button click stream (from click stream to accumulated stream to number of click stream and then filtered it) and then we reacted to the mutated button click stream. This paradigm is <em>FRP</em> as we used functional approach to do reactive programming.</p><h3>Conclusion</h3><p>I hope I have convinced you to try coding in <strong><em>Functional Reactive Programming </em></strong>and using <strong><em>RxJava</em></strong>. In the next post I will discuss some basics of RxJava. If you have any doubt or would like to correct this noob’s approach feel free to comment below.</p><p>If you feel the article did it’s job, hit the little green heart button below.</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e04a456d9de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/understanding-the-enigma-of-rxjava-part-1-8e04a456d9de">Understanding the enigma of RxJava (Part 1)</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>