<?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 Aditi Katiyar on Medium]]></title>
        <description><![CDATA[Stories by Aditi Katiyar on Medium]]></description>
        <link>https://medium.com/@aditik12329?source=rss-83d35774f4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-eey_asHioaF2V-uFyNB6g.jpeg</url>
            <title>Stories by Aditi Katiyar on Medium</title>
            <link>https://medium.com/@aditik12329?source=rss-83d35774f4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:22:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aditik12329/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[In-app updates on Android]]></title>
            <link>https://medium.com/@aditik12329/in-app-updates-on-android-14866506821a?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/14866506821a</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-developers]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 07:33:45 GMT</pubDate>
            <atom:updated>2022-12-29T07:33:45.459Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to show app updates to the user inside an Android app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeLt9i2ipA4wIR-EAZ0pBQ.jpeg" /><figcaption>Photo by Miguel Á. Padriñán: https://www.pexels.com/photo/close-up-shot-of-keys-on-a-red-surface-2882668/</figcaption></figure><p>Most of the users enable background updates for their apps when the device is connected to an unmetered connection. But if the app has not been updated and we want to prompt the user to update the app, Google provides its <em>Play Core</em> library to do so.</p><p>The in-app updates allow the user to update an app from within the app itself rather than going onto Playstore.</p><h4>Types of updates</h4><p>There are 2 types of updates — <em>Flexible</em>(the user can deny this type of update) &amp; <em>Immediate</em>(the user has to update the app forcibly, or else won’t be able to use the app).</p><p>Which type of update to show to the user depends on us. There can be multiple ways to do so. One intuitive idea is to check the current version of the app and show immediate updates to users who are on versions lower than <em>x</em> and flexible updates to users who are on versions above <em>x, </em>where <em>x</em> is the ‘minimum supported version’. You can build your own logic.</p><h4>How to know whether an update is available on Playstore?</h4><p>The <em>Play Core</em> library handles the in-app updates for us. Add the following dependency in your app’s <em>build.gradle </em>file.</p><pre>dependencies {<br>    implementation &#39;com.google.android.play:app-update:2.0.1&#39;<br>    implementation &#39;com.google.android.play:app-update-ktx:2.0.1&#39;<br>    ...<br>}</pre><p>Now create an object of <em>AppUpdateManager</em>. This object will let you check for updates, and handle them:</p><pre>val appUpdateManager = AppUpdateManagerFactory.create(context)</pre><p>Now check for updates using this:</p><pre>fun checkUpdate() {<br>    appUpdateManager.appUpdateInfo.addOnSuccessListener { appUpdateInfo -&gt;<br>        // update is available<br>        triggerAppUpdate(appUpdateInfo)<br>    }<br>}</pre><p>The <em>Play Core</em> library will internally check on Playstore whether an update is available or not. If yes, then you will receive <em>appUpdateInfo</em> in the success listener. Also note, that you won’t get any callback here if the device does not have Playstore on it.</p><p>Now once you know that an update is there, you need to decide whether to show a <em>Flexible</em> update or an <em>Immediate</em> update.</p><pre>fun triggerAppUpdate(appUpdateInfo: AppUpdateInfo) {<br>    // get the current app version from packageManager<br>    val currentVersion = context.packageManager.getPackageInfo(context.packageName, 0).longVersionCode<br><br>    // Let&#39;s say you maintain some minSupportedVersion on backend or Remote Config    <br>    val minSupportedVersion = repository.getMinSupportedVersion() <br>    <br>    if (currentVersion &lt; minSupportedVersion) {<br>        showImmediateUpdate(appUpdateInfo)<br>    } else {<br>        showFlexibleUpdate(appUpdateInfo)<br>    }<br>}</pre><h4>Immediate Update</h4><p>If you want to block the user from using the app without an update, go for an Immediate update. Call <em>startUpdateFlowForResult() </em>function to trigger the update process. Do it<em> </em>in the following cases:</p><ul><li>When an update is available. (<em>UpdateAvailability.UPDATE_AVAILABLE </em>state)</li><li>When an update was previously downloaded but not installed. So you should start the installation. (<em>InstallStatus.DOWNLOADED</em> state)</li><li>When the app returns to the foreground, resume the update. (check for <em>UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS</em> state)</li></ul><pre>fun showImmediateUpdate(appUpdateInfo: AppUpdateInfo) {<br>    if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE ||<br>        appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS ||<br>        appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED<br>    ) {<br>        appUpdateManager.startUpdateFlowForResult(<br>            // Pass the intent that is returned by &#39;getAppUpdateInfo()&#39;.<br>            appUpdateInfo,<br>            // AppUpdateType will be IMMEDIATE<br>            AppUpdateType.IMMEDIATE,<br>            // The current activity making the update request.<br>            activity,<br>            // Include a request code to later monitor this update request<br>            APP_UPDATE_REQUEST_CODE<br>        )<br>    }<br>}</pre><p>This will open a blocking UI. This is like another activity opening above your app. This activity is a part of the <em>Play Core</em> library. If you dismiss the dialog, you won’t be able to go back to your app, rather it will close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*IvUAEDuux5wc-Nzh.png" /></figure><p>To receive updates on in-app update installation, you can get the result in <em>onActivityResult()</em> callback:</p><pre>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {<br>    super.onActivityResult(requestCode, resultCode, data)<br>    if (requestCode == APP_UPDATE_REQUEST_CODE) {<br>        // Do on result<br>        if (resultCode == Activity.RESULT_CANCELED) {<br>            sendAnalytics(&quot;Update canclled by user&quot;)<br>        }<br>        . . .<br>    }<br>}</pre><h4>Flexible Update</h4><p>If it is not mandatory for the user to update the app, show a <em>Flexible</em> update. Here, you need to check if the install status is <em>InstallStatus.DOWNLOADED, </em>then simply complete the update. Otherwise, if an update is available or an update is in progress, start/resume it by calling the <em>startUpdateFlowForResult().</em></p><pre>fun showFlexibleUpdate(appUpdateInfo: AppUpdateInfo) {<br>    if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {<br>        showInstallAlert(onOKClick = {<br>            // call &#39;completeUpdate()&#39; <br>            appUpdateManager.completeUpdate()<br>        })<br>    } else if (<br>        appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS || <br>        appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE<br>    ) {<br>            appUpdateManager.startUpdateFlowForResult(<br>            // Pass the intent that is returned by &#39;getAppUpdateInfo()&#39;.<br>            appUpdateInfo,<br>            // AppUpdateType will be FLEXIBLE<br>            AppUpdateType.FLEXIBLE,<br>            // The current activity making the update request.<br>            activity,<br>            // Include a request code to later monitor this update request<br>            APP_UPDATE_REQUEST_CODE<br>        )<br>    }<br>}</pre><p>The user is shown a non-sticky dialog asking to update the app. If the user clicks on <em>“No Thanks”</em>, the dialog dismisses and the user continues to use the app as before without any update. If the user clicks on <em>“Update”</em>, the update downloads in the background, and the user continues to use the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*bpuy6MmNNifg925L.png" /></figure><p>However, when the download is complete, we get a callback from the <em>Play Core</em> library. To listen to the install updates, we have to register <em>InstallStateUpdatedListener</em> on the <em>appUpdateManager</em> object. This will let you listen to all the states:</p><pre>private val updateListener: InstallStateUpdatedListener = { state -&gt;<br>  when {<br>      state.installStatus() == InstallStatus.DOWNLOADED -&gt; {<br>         /*<br>         * When update has downloaded, ask user whether to install the update.<br>         * May be show some custom dialog saying:<br>         * &quot;Update download is complete. Do you want to install?&quot; with 2 <br>         * action buttomns - &quot;Yes&quot; &amp; &quot;No&quot;<br>         */<br>      }<br><br>      state.installStatus() == InstallStatus.CANCELED -&gt; {<br>         /*<br>         * User has cancelled <br>         */<br>      }<br>         <br>      state.installStatus() == InstallStatus.DOWNLOADING -&gt; {<br>          /* <br>          * while update download is in progress, <br>          * you can show some progress bar withint the app<br>          */<br>      }<br>}<br>appUpdateManager.registerListener(updateListener)<br><br>.<br>.<br>.<br>/*<br>* unregister the listener when not needed<br>*/<br>appUpdateManager.unregisterListener(updateListener)</pre><p>Once the installation starts, the Play Core library displays a full-screen sticky UI. During installation, the user cannot use the app. Once complete, the app is restarted by itself.</p><h4>Points to remember</h4><ul><li>Always check for updates in <em>onResume()</em> of your activity. This way you make sure that you are not missing updates even during an app session.</li><li>unregister <em>InstallStateUpdatedListener </em>when not in use, like in <em>onPause()</em>, to avoid memory leaks.</li><li>In the case of flexible updates, do not spam your users with an update dialog every time they open your app. Instead, show the flexible update dialog once in a while. e.g. once a week or so. You can maintain the last timestamp when an update was shown in shared pref, and the next time you are about to show a flexible update, check the difference between the current time and the last timestamp.</li></ul><h4>How to test in-app updates?</h4><p>Create 2 production builds(testing on debug builds will not work because we only upload production builds on PlayStore.), one with lower version code &amp; other with higher version code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*05V2k_sXwMRk29hUbTfm5g.png" /></figure><p>Go to internal app sharing on Play console and click this link. It will open an internal app-sharing dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*tfkVA2YwniJoq-Xc.gif" /><figcaption>image <a href="https://stackoverflow.com/questions/57478894/how-to-enable-internal-app-sharing-for-android">source</a></figcaption></figure><p>Upload both builds here. First, install the lower version build on your device(it must have Play Store) using the link. Open the app and run. Then click the link for the higher-version build. Do not install it. Rather go to the app and you should see the update.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14866506821a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Android Jetpack Compose?]]></title>
            <link>https://write.agrevolution.in/what-is-android-jetpack-compose-14c51b46be35?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c51b46be35</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 06:42:31 GMT</pubDate>
            <atom:updated>2021-11-30T06:42:31.978Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with Android’s new UI toolkit.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ND9_fTdKbc5tXWvGxp94Pw.jpeg" /><figcaption>by <a href="https://www.imdb.com/title/tt0042569/"><strong>imdb</strong></a></figcaption></figure><p>A few months back, Google released the production-ready version of the Jetpack Compose library. This library defines the new toolkit for creating the UI! The main purpose of this library is to upscale Android app development by allowing us to do everything in one common language — Kotlin.</p><h4>Why use Jetpack Compose?</h4><ul><li>We no longer need to write our UI or navigation graph in XML. They are written directly in Kotlin, along with all the business logic.</li><li>With Compose, we write lesser lines of code. Hence lesser to test, maintain and understand.</li><li>It follows a more declarative approach — we specify the UI within the Activity itself in Kotlin. Whereas with the old way of app development, we had two separate entities — Activity and XML UI, and we connected both of them with each other according to our business logic.</li><li>It significantly reduces the app size because we have to write lesser code.</li></ul><p>We can read more on the official <a href="https://developer.android.com/jetpack/compose/why-adopt">documentation</a>.</p><h4>How does Compose work?</h4><p>This toolkit is based on the <em>composite design pattern,</em> hence the word — <em>Compose</em>. To get a better understanding of the composite design pattern, we can read <a href="https://medium.com/@aditik12329/composite-design-pattern-a475dbf97312">Composite Design Pattern</a>.</p><p>Up till now, we have been creating views in XML where every view element(TextView, EditText, Button, etc.) inherited properties from another View element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0j22EM-t5xyJM1pvibL3g.png" /></figure><p>This type of structure prohibits us from introducing additional functionalities in a view. e.g. If we want a button with 2 images within it, then we cannot do it with the original <em>Button</em> class of Android. We would have to create a custom view.</p><p>But with <em>compose</em>, we do not need to take so much pain! <em>Compose</em> is based on the composite design framework, where, every view can contain one or more child views within it, and the child views can further have sub-child views within them and so on. Also, we can treat a group of views the same as we would treat a single view. e.g. both, a single view and group of views can have the same attributes like padding, gravity, background color, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-31Ppvl0_G5U4pp_oYYyA.png" /></figure><p>Thus we can directly add 2 <em>Image</em>s in a <em>Button</em> in compose, and the code will look like this:</p><pre><strong><em>Button</em></strong>(onClick = <strong>{  }</strong>) <strong>{<br>    <em>Row </em>{<br>        <em>Image</em></strong>(<br>            painter = <em>painterResource</em>(id = R.drawable.img_1),<br>            contentDescription = &quot;tmp&quot;,<br>            modifier = Modifier<br>                .<em>size</em>(80.<em>dp</em>)<br>                .<em>padding</em>(8.<em>dp</em>),<br>            contentScale = ContentScale.Crop<br>        )<br>        <strong><em>Image</em></strong>(<br>            painter = <em>painterResource</em>(id = R.drawable.img_2),<br>            contentDescription = &quot;tmp&quot;,<br>            modifier = Modifier<br>                .<em>size</em>(80.<em>dp</em>)<br>                .<em>padding</em>(8.<em>dp</em>),<br>            contentScale = ContentScale.Crop<br>        )<br>    <strong>}<br>}</strong></pre><p>Notice how easily we are able to add images in a button(Do not mind the remaining code, we’ll understand it as we learn more).</p><h4>How to write code in <em>compose</em>?</h4><p>We need to add at least the below dependencies in <em>build.gradle</em> to get started with basics.</p><pre>implementation &quot;androidx.compose.ui:ui:$compose_version&quot;<br>implementation &quot;androidx.compose.material:material:$compose_version&quot;<br>implementation &quot;androidx.compose.ui:ui-tooling-preview:$compose_version&quot;<br>implementation &quot;androidx.compose.runtime:runtime-livedata:$compose_version&quot;</pre><p>Create a <em>compose</em> activity by going to <em>New &gt; Compose&gt; Empty Compose Activity.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HU7buN7LNmkldFeYdm4JQw.png" /></figure><p>We get the following code generated for us:</p><pre>class MyComposeActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <strong>setContent</strong> <strong>{<br>            <em>TryComposeTheme</em></strong><em> </em><strong>{<br>                </strong>// A surface container using the &#39;background&#39; color from the theme<br>                <strong><em>Surface</em></strong>(color = MaterialTheme.colors.background) <strong>{<br>                    Greeting</strong>(&quot;Android&quot;)<br>                <strong>}<br>            }<br>        }<br>    </strong>}<br>}<br><strong><br>@Composable</strong><br>fun <strong>Greeting</strong>(name: String) {<br>    <strong><em>Text</em></strong>(text = &quot;Hello $name!&quot;)<br>}<br><br><strong>@Preview</strong>(showBackground = true)<br><strong>@Composable</strong><br>fun DefaultPreview() {<br>    <strong><em>TryComposeTheme</em></strong><em> </em><strong>{<br>        Greeting</strong>(&quot;Android&quot;)<br>    <strong>}<br></strong>}</pre><p>The views in compose are actually functions that have lots of arguments for properties. Let us look at the documentation of <strong>Text</strong> in the code <strong><em>Text</em>(text = “Hello $name!”)</strong>:</p><pre><strong>@Composable</strong><br>fun Text(<br>    <strong>text</strong>: AnnotatedString,<br>    <strong>modifier</strong>: Modifier = Modifier,<br>    <strong>color</strong>: Color = Color.Unspecified,<br>    <strong>fontSize</strong>: TextUnit = TextUnit.Unspecified,<br>    <strong>fontStyle</strong>: FontStyle? = null,<br>    <strong>fontWeight</strong>: FontWeight? = null,<br>    <strong>fontFamily</strong>: FontFamily? = null,<br>    .<br>    .<br>    .<br>) {<br>    .<br>    .<br>    .<br>}</pre><p><strong><em>Text</em></strong> element is provided by the library itself(It is a replacement for <em>TextView). </em>We see that <strong>it is a function</strong> which has various arguments like — text, color, fontSize, fontStyle, etc. We used to specify all of this in XML. In <em>compose</em>, we can specify this in the Kotlin code itself! We can also explore other classes like <em>Button, Surface,</em> etc.</p><p>Note the <strong><em>@Composable</em></strong> annotation. Its documentation reads:</p><blockquote>Composable functions are the fundamental building blocks of an application built with Compose. . .</blockquote><p>It means that this annotation defines the basic building block of the UI in compose. All the UI elements in <em>compose </em>are actually functions with @Composable annotation. A @Composable function can only be called from another @Composable function. This type of structure increases the reusability of the UI elements. e.g. If we define a composable of a button with 2 images in it, then we can easily plug it in anywhere in a complex view hierarchy.</p><p>The <em>Greeting</em> function is also @Composable which is called from another composable — <em>Surface.</em></p><p><em>Surface</em> specifies the background of the UI element. The <em>Surface </em>is called from another composable — <em>TryComposeTheme </em>(where ‘TryCompose’ is the project name).</p><p><em>TryComposeTheme{ } </em>wraps our UI in the theme used by our project(we can omit this and call the <em>Greeting</em> directly from <em>setContent </em>if we don’t want to use our project’s theme for the UI).</p><p><em>setContent { }</em> is a lambda function, where we call the parent composable to initialise our UI. It is the replacement for <em>setContentView(</em>@LayoutRes int layoutResID<em>) </em>&amp;<em> setContentView(View view) </em>methods.</p><p>So, the view hierarchy goes like this: <em>TryComposeTheme </em>composable is the parent UI element that has &gt; <em>Surface </em>composable that has &gt; <em>Greeting </em>composable that has &gt; <em>Text</em> composable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXO293i6ZtvKDX92ItonNA.png" /></figure><p>The preview looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*9qAosNt-lVPK4R4yr8LTLw.png" /></figure><p>The <strong><em>@Preview</em></strong> annotation on a composable renders the preview of our view in the IDE. It is a very helpful annotation that helps us to see how our UI is going to look like.</p><p>We’ll see more about <em>compose</em> in future articles.</p><p>Thanks for reading! If you liked it, please give it a clap!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c51b46be35" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/what-is-android-jetpack-compose-14c51b46be35">What is Android Jetpack Compose?</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composite Design Pattern]]></title>
            <link>https://medium.com/@aditik12329/composite-design-pattern-a475dbf97312?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a475dbf97312</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 16:27:20 GMT</pubDate>
            <atom:updated>2021-11-18T16:27:20.118Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is a composite design pattern? How to solve a real-world problem with it?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Ee1Ew_6W3QiTQ0RaBLEl-w.jpeg" /><figcaption>by <a href="https://www.istockphoto.com/vector/angular-vector-pattern-design-abstract-background-gm1275326600-375732040"><strong>istock</strong></a></figcaption></figure><p>The word <em>composite</em> means “made up of different things or a collection of something”. In the context of design patterns, a <em>composite</em> would mean a collection of objects. Sometimes, as the user of a code, we would like to treat a collection of objects in the same way we treat a single object. This means that both, the single object and the collection of objects should implement the same functionality. We can achieve this by using the <em>composite </em>design pattern.</p><h4>What problem does it solve?</h4><p>The composite design pattern is mostly applicable in cases where data forms some sort of hierarchy. Let us understand this with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4hMN-xVVeDRxGrKDXuBpA.png" /><figcaption>a hypothetical course structure</figcaption></figure><p>We can represent a course structure in the form of a tree, where topics — science and mathematics, have sub-topics within them, and the sub-topics might have sub-sub-topics further, and so on.</p><p>Note that some nodes do not have children, whereas some do. Nodes that do not have children are called <em>leaf nodes</em>. Nodes that have children(<strong>or have a collection of nodes</strong>) can be called <em>composite nodes</em>(because they are composed of a collection of nodes).</p><p>Now, if we want to know whether the course is completed, we need to know whether topics — science &amp; mathematics are completed. In order to know whether the topic — science is completed, we need to know whether topics — physics, chemistry &amp; biology are completed. So in short, we have to recurse down the tree and determine at each node, whether the topic was completed or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a038e2f606fd7948b340c9a1fa3943/href">https://medium.com/media/d1a038e2f606fd7948b340c9a1fa3943/href</a></iframe><p>One important point to note in the function — <em>isCourseCompleted() </em>is that we are <strong>using an <em>if-else</em> statement to differentiate between leaf and composite nodes</strong>. At every step of recursion, we are making a decision based on the type of node, i.e., leaf or composite node.</p><p>The composite pattern will eliminate this <em>if-else</em> check by making the group of objects and the independent objects implement the same interface(functionality). It will treat the leaf and composite nodes in the same way.</p><h4>Sketching out the Class diagram</h4><p>In the above course structure example, we see that the leaf nodes(green- colored) — Biology, Laws of Motion, Gravitation, etc. are topics in a course. The composite nodes(red-colored) like — Science, Mathematics, Physics, etc. are also topics that contain a list of topics within them. In this example, we can call a composite node(a node that contains a collection of nodes) as a “Course” which contains a list of topics to study within it.</p><p>If we want both leaf(<em>Topics</em>) and composite(<em>Course</em>) nodes to have the same functionality, then both of them should inherit the same interface(i.e. <em>ITopic</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7x_tfH4G8xFKY25NBKb9A.png" /></figure><p>And since a “Course” has a list of topics within it, so the final class diagram looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIx5--z1GPUpE2DONgNG0g.png" /></figure><p>Note that a course can have both, courses and independent topics, within it.</p><h4>Writing code with the pattern</h4><p>We define an interface <em>ITopic</em> that specifies the functionality — <em>isCompleted().</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a275351eca47e0d1280bf132987dde9/href">https://medium.com/media/1a275351eca47e0d1280bf132987dde9/href</a></iframe><p>We create a concretion of <em>ITopic — Topic.</em> The class <em>Topic</em> has defined its own implementation of the functionality — <em>isCompleted().</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4af470e48c53b11ec6a4e33c7f7b563a/href">https://medium.com/media/4af470e48c53b11ec6a4e33c7f7b563a/href</a></iframe><p>We create another concretion of <em>ITopic — Course</em>. The class <em>Course</em> <strong>has-A </strong>list of <em>ITopics.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11d5950d620f821c5d628291585865a9/href">https://medium.com/media/11d5950d620f821c5d628291585865a9/href</a></iframe><p>Note the line of code :</p><pre>isCourseCompleted &amp;= <strong>topic.isCompleted()</strong>;</pre><p>Here, we do not worry whether the topic is a leaf node(<em>Topic</em>) or a composite node(<em>collection of Topics or, a Course</em>). If the topic is a leaf node, it will return the result normally. If it is a composite node, it will recursively fetch the result from the subsequent nodes. Thus we are able to eliminate the <em>if-else</em> check(node type-based decision) because of the composite design pattern!</p><p>This is a very general idea of the composite design pattern. For a detailed explanation, you can refer to this awesome <a href="https://www.youtube.com/watch?v=EWDmWbJ4wRA">video</a>, which I referred initially to get an in-depth understanding.</p><p>Thanks for reading! If you liked it, please give it a clap! Keep Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a475dbf97312" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines(Part — 5): Exception Handling]]></title>
            <link>https://write.agrevolution.in/kotlin-coroutines-part-5-exception-handling-46e342d07f4c?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e342d07f4c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 12:13:32 GMT</pubDate>
            <atom:updated>2021-09-15T12:13:32.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines(Part — 5): Exception Handling</h3><h4>How to handle exceptions thrown by coroutines?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-i0fzeyzr7V5dmp9OD9ug.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@alleksana?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">alleksana</a> from <a href="https://www.pexels.com/photo/wood-dirty-writing-abstract-4271933/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>One needs to handle exceptions in a coroutine to facilitate a smooth user experience. We can handle exceptions in 2 ways — by using a try-catch block or <em>CoroutineExceptionHandler</em>. Which one to use depends on what we want to do when an exception occurs.</p><p>Let’s look at an example job hierarchy in which <em>Job1</em> throws an exception.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7ea490d94b1c03dc93a6c153b98f868/href">https://medium.com/media/f7ea490d94b1c03dc93a6c153b98f868/href</a></iframe><p>Both <em>Job1</em> &amp; <em>Job2</em> are running in the same scope. Note that <em>Job1</em> takes 200ms and <em>Job2</em> takes 500ms to finish(Job2 takes more time than Job1). We are simulating this with the help of <em>delay()</em> function.</p><p>If we run the above code, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JsFsglE2LHpXxC-pyCwTQ.png" /></figure><p><em>Job2 </em>is cancelled because it was running when <em>Job1 </em>threw an exception. The moment <em>Job1 </em>threw the exception, it forced the entire job hierarchy to shut down and the code crashed.</p><h4>try-catch block</h4><p>It is used when we want to recover from exceptions. Using this will not propagate the exception upwards in the job hierarchy and the remaining portion of the job tree can continue execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/accb859b3091131b57db7984feee6dce/href">https://medium.com/media/accb859b3091131b57db7984feee6dce/href</a></iframe><p>Here, we put try-catch around <em>someExceptionThrowingWork()</em> function in <em>Job1</em>. If we run the above code, we’ll get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pC7uzKokcDZ1Oz2aXZTHlA.png" /></figure><p>The code did not crash, and <em>Job2 </em>was able to finish even though <em>Job1</em> threw an exception. The try-catch helped to recover from the exception and the remaining job was able to finish.</p><h4>CoroutineExceptionHandler</h4><p>It is one of the context elements which is optional to pass while creating a coroutine. It helps us handle uncaught exceptions. We use this when we do not want to recover from the exception. If any coroutine fails, the entire job hierarchy shuts down and the exception is handled by our <em>CoroutineExceptionHandler</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b95f6975ad827fae16301e46ed95d46b/href">https://medium.com/media/b95f6975ad827fae16301e46ed95d46b/href</a></iframe><p>Here, we are installing a <em>CoroutineExceptionHandler </em>at the parent level scope. If we run the above code, we’ll get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17umQLceT3Gtt0A2z5WaZQ.png" /></figure><p>Again, the code did not crash. But, <em>Job2</em> is cancelled(unlike try-catch where <em>Job2 </em>is finished). This is because when <em>Job1</em> threw an exception, it propagated up the job-tree, the <em>CoroutineExceptionHandler</em> at the parent’s scope cancelled all the running jobs and shut down the entire job hierarchy.</p><p><em>CoroutineExceptionHandler </em>should be used as a last resort for global ‘catch-all’ behavior.</p><p>If you want to learn more about coroutines, check these out:</p><ul><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-1-the-basics-56c88903129a">Kotlin Coroutines(Part — 1): The Basics</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-2-the-suspend-function-95ebee74bfc8">Kotlin Coroutines(Part — 2): The ‘Suspend’ Function</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-3-coroutine-context-bd5543389190">Kotlin Coroutines(Part — 3): Coroutine Context</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-4-cancellation-811cd5a9813a">Kotlin Coroutines(Part — 4): Cancellation</a></li></ul><p>Thanks for reading! If you liked it, please give it a clap! Keep Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e342d07f4c" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/kotlin-coroutines-part-5-exception-handling-46e342d07f4c">Kotlin Coroutines(Part — 5): Exception Handling</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines(Part — 4): Cancellation]]></title>
            <link>https://write.agrevolution.in/kotlin-coroutines-part-4-cancellation-811cd5a9813a?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/811cd5a9813a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 11:31:42 GMT</pubDate>
            <atom:updated>2021-09-18T18:56:17.662Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines(Part — 4): Cancellation</h3><h4>How and when to cancel coroutines?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAvy65XHVPUw5w55fMxqbg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@jeffrey-czum-254391?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Jeffrey Czum</a> from <a href="https://www.pexels.com/photo/concrete-building-under-blue-sky-4004291/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Whenever we create a coroutine, we shall always remember to cancel it. Otherwise, it can cause memory leaks or unnecessary updates to UI.</p><p>When we create a coroutine, we get a ‘job’ object. A job can be cancelled as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d8b2a95f1c502a7090bc81db50c38a3/href">https://medium.com/media/7d8b2a95f1c502a7090bc81db50c38a3/href</a></iframe><p>When we cancel a job, it throws a <strong>CancellationException</strong>. Unlike other exceptions, it does not crash the program. It is a silent exception that moves up the job hierarchy, but no special action is taken. The coroutine is cancelled normally.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/824025026156e95f509bb9deda883ef3/href">https://medium.com/media/824025026156e95f509bb9deda883ef3/href</a></iframe><p>Here, if the job is cancelled before the coroutine completes, then it will throw a CancellationException and prints ‘Coroutine is Cancelled!’.</p><h4>Structured Concurrency</h4><p>Coroutines follow a <a href="https://en.wikipedia.org/wiki/Structured_concurrency">structured concurrency</a> paradigm. It means that coroutines have cleaner entry &amp; exit points, ensuring that a coroutine finishes only when its children finish. Such execution allows errors to be propagated to the parent(or root) coroutine and child coroutines do not leak out(or become orphaned).</p><p>There are 5 properties of structured concurrency which coroutines follow:</p><p><strong>1. Every coroutine starts in a logical scope</strong></p><p>Coroutine should have a limited lifetime, or in other words, every scope should have a lifecycle. We need to track when to cancel the coroutine if it is running. It is the same as collecting observables in RxJava and disposing of them.</p><p>We can either create our coroutines in <em>viewModelScope</em> or <em>lifecycleScope</em>, or we can create our own scope and cancel it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1c1e64a6302b492554794a68963cfc/href">https://medium.com/media/ce1c1e64a6302b492554794a68963cfc/href</a></iframe><p>Here, <strong>cancelling the scope</strong> will cancel all the coroutines running in this scope.</p><p><strong>2. Coroutines started in the same scope form a job hierarchy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfhHdC9u0igJd8e5zYJHkA.png" /></figure><p>Jobs started in a coroutine become children of the parent’s job. The child coroutines inherit all the context elements except the ‘Job’ object.</p><p>If <em>Job0</em> is started on the Main thread, then by default its child jobs — <em>Job1</em> &amp; <em>Job2</em> will also start on the Main thread, and so on.</p><p><strong>3. A parent job won’t complete until all of its children have completed</strong></p><p>In the above example, <em>Job0 </em>will not be complete unless <em>Job1 </em>&amp; <em>Job2 </em>are complete. And <em>Job2 </em>will not be complete unless <em>Job3 </em>&amp; <em>Job4 </em>are complete.</p><p><strong>4. Cancelling a parent cancels its children recursively</strong></p><p>If we cancel <em>Job0</em>, then it will cancel <em>Job1 </em>&amp; <em>Job2</em>. And <em>Job2 </em>will further cancel <em>Job3 </em>&amp; <em>Job4</em>. However, cancelling a job does not cancel its sibling. e.g. cancelling <em>Job2</em> will not cancel <em>Job1</em>.</p><p><strong>5. If a child coroutine fails, the exception propagates upwards in the job hierarchy, and depending on the parent job type, either all siblings are cancelled or none.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-K5j6ixjAxT4YW_pPUTmg.png" /></figure><p>If an exception occurs at <em>Job4</em>, then it is propagated to its parent, <em>Job2</em>, and <em>Job2 </em>further propagates the exception to <em>Job0</em>.</p><h4>Supervisor Job</h4><p>By default, a coroutine starts with a simple ‘Job’ element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HDNphW3IHAiOt-k_prHJQ.png" /></figure><p>If <em>Job1 </em>throws an exception, then <em>Job2</em>(which was started in the same scope) will be cancelled. But if we don’t want <em>Job2 </em>to get cancelled, then we have to use ‘SupervisorJob’ instead of the simple ‘Job’ element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13cfcf37a7c941a1aac2d70671501cad/href">https://medium.com/media/13cfcf37a7c941a1aac2d70671501cad/href</a></iframe><p>We can also change the context elements in a child coroutine if we specify them explicitly like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b31a70a8e1ff7cafc0badc13d4378ed3/href">https://medium.com/media/b31a70a8e1ff7cafc0badc13d4378ed3/href</a></iframe><p>If you want to learn more about coroutines, check these out:</p><ul><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-1-the-basics-56c88903129a">Kotlin Coroutines(Part — 1): The Basics</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-2-the-suspend-function-95ebee74bfc8">Kotlin Coroutines(Part — 2): The ‘Suspend’ Function</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-3-coroutine-context-bd5543389190">Kotlin Coroutines(Part — 3): Coroutine Context</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-5-exception-handling-46e342d07f4c">Kotlin Coroutines(Part — 5): Exception Handling</a></li></ul><p>Thanks for reading! If you liked it, please give it a clap! Keep Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811cd5a9813a" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/kotlin-coroutines-part-4-cancellation-811cd5a9813a">Kotlin Coroutines(Part — 4): Cancellation</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines(Part — 3): Coroutine Context]]></title>
            <link>https://write.agrevolution.in/kotlin-coroutines-part-3-coroutine-context-bd5543389190?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5543389190</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 10:43:47 GMT</pubDate>
            <atom:updated>2021-09-18T18:54:57.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines(Part — 3): Coroutine Context</h3><h4>What does a CoroutineScope consist of? How to switch the context of a coroutine?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*dG5RfFWE8Pt0JMtx.jpeg" /></figure><p>Let us try to understand <em>CoroutineScope</em> in depth<em>.</em> The documentation of <em>CoroutineScope</em> class reads as follows:</p><blockquote><em>“Creates a CoroutineScope that wraps the given coroutine context.<br>If the given context does not contain a Job element, …”</em></blockquote><p>For now, we are only going to focus on the term <em>coroutine context.</em></p><h4>What is a coroutine context?</h4><p>Coroutines always execute in some context represented by a value of the <a href="https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html">CoroutineContext</a> type.</p><p>A ‘CoroutineContext’ is defined in the scope in which we start the coroutine. It is a collection of several ‘context’ elements -</p><ol><li>Dispatcher(which thread to run on)</li><li>Job(control the lifecycle of coroutine)</li><li>error handler(handle errors when a coroutine throws an exception)</li><li>name(name of the coroutine)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*zfczumO5AsG80pyj.png" /><figcaption>Dispatcher, Job, Error Handler &amp; Name are the context elements of a coroutine</figcaption></figure><h4>The ‘withContext()’ function</h4><p>It is a suspending function that is used to shift the execution of the current coroutine on a new <em>CoroutineContext</em>, in most cases, a different dispatcher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*XYGQ4c81zouP3PYr.png" /></figure><p>We have launched a coroutine on the background thread(<em>Dispatchers.IO</em>). The function <em>apiService.getImage()</em> executes on the background thread. After we get the image url, we want to show the image file in an ImageView. So we change the context(or the underlying thread) of our coroutine with the help of <em>withContext(Dispatchers.Main)</em>.</p><p>Note that <em>withContext()</em> is a suspending function, which means that it will make the caller coroutine <strong>wait</strong> until the code within <em>withContext()</em> executes.</p><p>Let’s look at a few coroutine scopes and their context elements provided by the kotlinx-coroutines library.</p><h4>viewModelScope</h4><p><em>viewModelScope</em> is a coroutine scope bound to the lifetime of a ViewModel, i.e., a coroutine started in <em>viewModelScope</em> will be cancelled when the ViewModel clears.</p><p><strong>Dispatcher: </strong><em>viewModelScope</em> uses <em>Dispatchers.Main.immediate</em> as the dispatcher by default. It optimises performance by immediately starting execution on the Main thread.</p><p><strong>Job: </strong><em>viewModelScope </em>uses <em>SupervisorJob</em> as the job element, which means that if a coroutine in <em>viewModelScope</em> throws an exception, the other coroutines in the same scope will continue to run, while the one that caused the exception will terminate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*BF50NwhlsHq8xgmX.png" /></figure><h4>lifecycleScope</h4><p><em>lifecycleScope</em> is a coroutine scope bound to the lifetime of a LifecycleOwner(Activity or Fragment), i.e., a coroutine started in <em>lifecyleScope</em> will be cancelled when <em>onDestroy()</em> of Activity/Fragment is called.</p><p><strong>Dispatcher:</strong> <em>lifecycleScope</em> uses <em>Dispatchers.Main.immediate</em> as the dispatcher by default(just like <em>viewModelScope</em>).</p><p><strong>Job:</strong> It uses <em>SupervisorJob</em> as the job element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*isNnZ-tSc9tlp4dM.png" /><figcaption>save list in local database and send analytics event after save is complete</figcaption></figure><p><em>lifecycleScope</em> is useful for UI operations like animations, etc. There are various functions to create coroutines in this scope:</p><ul><li>launch{ }</li><li>launchWhenCreated{ }: starts when lifecycle is at least in Lifecycle.State.CREATED state</li><li>launchWhenStarted{ } : starts when lifecycle is at least in Lifecycle.State.STARTED state</li><li>launchWhenResumed{ }: starts when lifecycle is at least in Lifecycle.State.RESUMED state</li></ul><h4>viewLifecycleOwner.lifecycleScope</h4><p>In an Activity/Fragment, we have a view’s lifecycle owner — <em>viewLifecycleOwner</em>. This controls the lifecycle of a view. Its lifecycle starts when <em>onCreateView()</em> is called and destroys when <em>onDestroyView()</em> is called.</p><p>Thus, the coroutine started in v<em>iewLifecycleOwner.lifecycleScope</em> will be cancelled when <em>onDestroyView()</em> is called. It has the same context elements as <em>lifecycleScope</em>. Use this scope when you think that running your coroutine beyond <em>onDestroyView()</em> might access your views and cause exceptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*QoWSeAULM_bN6Tvd.png" /><figcaption>collecting a flow in Fragment/Activity</figcaption></figure><h4>creating our own scope</h4><p>While creating a scope with <em>CoroutineScope</em>, we have to pass at least one context element. We can pass a dispatcher. We can also specify the ‘Job’ element and exception handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fac2773e4e94dfe5a0043262d50ff993/href">https://medium.com/media/fac2773e4e94dfe5a0043262d50ff993/href</a></iframe><p>The scope of a coroutine decides its lifetime. When a scope ends, the coroutine also cancels if it is running, hence preventing leaks. The scopes provided by kotlinx-coroutines library start a coroutine on the Main thread by default. Its underlying context elements(like Dispatcher) can be changed according to our needs.</p><p>To learn more about coroutines, check these out:</p><ul><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-1-the-basics-56c88903129a">Kotlin Coroutines(Part — 1): The Basics</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-2-the-suspend-function-95ebee74bfc8">Kotlin Coroutines(Part — 2): The ‘Suspend’ Function</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-4-cancellation-811cd5a9813a">Kotlin Coroutines(Part — 4): Cancellation</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-5-exception-handling-46e342d07f4c">Kotlin Coroutines(Part — 5): Exception Handling</a></li></ul><p>Thanks for reading! If you liked it, please give it a clap! Keep Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5543389190" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/kotlin-coroutines-part-3-coroutine-context-bd5543389190">Kotlin Coroutines(Part — 3): Coroutine Context</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines(Part — 2): The ‘Suspend’ Function]]></title>
            <link>https://write.agrevolution.in/kotlin-coroutines-part-2-the-suspend-function-95ebee74bfc8?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/95ebee74bfc8</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 05:17:49 GMT</pubDate>
            <atom:updated>2021-09-18T18:53:34.472Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines(Part — 2): The ‘Suspend’ Function</h3><h4>What are suspend functions, and how to make an API call using coroutines?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZoOgVLXxVAtFMyUavaVZw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@kelly-lacy-1179532?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Kelly Lacy</a> from <a href="https://www.pexels.com/photo/yellow-wait-signage-3129810/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Before moving further, if you want to have a basic idea of coroutines, check this out: <a href="https://write.agrevolution.in/kotlin-coroutines-part-1-the-basics-56c88903129a">Kotlin Coroutines(Part — 1): The Basics</a>.</p><p>The most common use-case of background processing is fetching data from servers (API calls). The most common approach will be to implement callbacks for success and failure cases. But what if we have to make 2 or more API calls one after another? We will be implementing callbacks for every API call within another API call. This is known as ‘callback hell’.</p><p>With coroutines, we can avoid ‘callback hell’ and make our code easily testable and readable!</p><h4>What is a suspend function?</h4><p>A ‘suspend’ function forces the caller coroutine to <strong>wait</strong> for the function completion without blocking itself. While the suspend function is executing, the coroutine releases the thread on which it was running and allows other coroutines to access that thread(Because coroutines are <strong>cooperative</strong>).</p><p>Let’s look at an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5OSJ4akKDtUnEFPbsQUwg.png" /></figure><p>We start a coroutine on <em>Dispatchers.IO </em>and call <em>loadNthFibonacciNumber(n). </em>We will learn about the underlying implementation of <em>loadNthFibonacciNumber(n: Int)</em> in the future(when we have a relatively better understanding of coroutines). For now, all we know is that it is calculated on <em>Dispatchers.Default</em> and is a suspend function.</p><p>While the function <em>loadNthFibonacciNumber</em> is executing on <em>Dispatchers.Default, </em>it ‘suspends’ the execution of the caller coroutine. The coroutine will <strong>wait </strong>for <em>loadNthFibonacciNumber</em> to finish. Meanwhile, this coroutine will release the <em>IO</em> thread and allow other coroutines to access that thread.</p><p>This is the reason why <em>loadNthFibonacciNumber</em> is a suspend function(because it suspends/halts the execution of caller coroutine and forces it to yield its resources so that others can use those resources).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGIMaOBql7bCVhrJUz2RGQ.png" /></figure><p>A suspend function can also be called from another suspend function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJ4zOZQUd7qekHZjOhFBGw.png" /></figure><h4>How to make API calls in Retrofit with coroutines?</h4><p>Let us fetch a list of Dogs from an API. The data class looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0806c3c35ff89f229bb06c1028645a5e/href">https://medium.com/media/0806c3c35ff89f229bb06c1028645a5e/href</a></iframe><p>Make the API call in the service class a ‘suspend’ function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d36160e67e52ae805e7c18f2eca415f6/href">https://medium.com/media/d36160e67e52ae805e7c18f2eca415f6/href</a></iframe><p>Here, we wish to get a list of dogs from the API. Now make the call in the repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a358626b2ff7f7cd1d4c5d55e20cc91/href">https://medium.com/media/6a358626b2ff7f7cd1d4c5d55e20cc91/href</a></iframe><p>Here, ‘ApiService’ is the same retrofit object that we used when calls were handled using callback listeners.</p><p>Since we can call a suspend function only from a suspend function or a coroutine scope, we added the ‘suspend’ modifier to the function ‘<em>fetchFromServer()’</em> here. This function is supposed to return <em>List&lt;Dog&gt;</em>. We put the API call — ‘<em>apiService.getDoggos()</em>’ in a try-catch block to catch the exceptions like — IOException, HttpException, etc. In case of exceptions, we can log them and return an empty list.</p><p>Now, we call the function ‘<em>fetchFromServer()</em>’ from the ViewModel as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc4c6edf4771d54464236029aa63338/href">https://medium.com/media/fdc4c6edf4771d54464236029aa63338/href</a></iframe><p>This is where we initiate the API call. We create a coroutine in <em>viewModelsScope </em>(so that the call cancels when ViewModel clears), and call our API through the repository’s code. Simply call the function <em>loadDoggos()</em> from Fragment/Activity to load data from the server and receive it by observing the LiveData <em>doggos</em>.</p><p>Note that we did not specify which thread to use for API calls. This is because Retrofit implicitly handles it on a background thread(and returns the result on the caller thread, which is the Main thread in this case) the moment we make the calls using suspend functions(Coroutines).</p><p>Writing API calls this way takes lesser time and less code, and hence becomes easier to test.</p><p>To learn more about coroutines, check these out:</p><ul><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-3-coroutine-context-bd5543389190">Kotlin Coroutines(Part — 3): Coroutine Context</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-4-cancellation-811cd5a9813a">Kotlin Coroutines(Part — 4): Cancellation</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-5-exception-handling-46e342d07f4c">Kotlin Coroutines(Part — 5): Exception Handling</a></li></ul><p>Thanks for reading! If you liked it, please give it a clap! Keep Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95ebee74bfc8" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/kotlin-coroutines-part-2-the-suspend-function-95ebee74bfc8">Kotlin Coroutines(Part — 2): The ‘Suspend’ Function</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutines(Part — 1): The Basics]]></title>
            <link>https://write.agrevolution.in/kotlin-coroutines-part-1-the-basics-56c88903129a?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/56c88903129a</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[multitasking]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 05:42:20 GMT</pubDate>
            <atom:updated>2021-09-18T18:51:17.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Coroutines(Part — 1): The Basics</h3><p>Getting started with Coroutines in Kotlin for Android Apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZUiMFvbvjqV6mHlkNTgfA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@pixabay?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pixabay</a> from <a href="https://www.pexels.com/photo/brown-and-white-track-field-163444/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Asynchronous programming is inevitable while developing Android apps. We do some tasks on a background thread and publish the results on the UI thread. For this, we usually implement ‘AsyncTask’.</p><p>With Kotlin Coroutines, we no longer need to implement the hefty callbacks. Coroutines help us to write async code in a sequential and imperative fashion, hence it becomes easier to write tests and debug. They also optimize app performance by spawning minimum possible threads(Multiple coroutines can run on a single thread!).</p><h3>What are coroutines?</h3><p>Wikipedia says -</p><blockquote>“Coroutines are computer program components that generalize <a href="https://en.wikipedia.org/wiki/Subroutine">subroutines</a> for <a href="https://en.wikipedia.org/wiki/Non-preemptive_multitasking">non-preemptive multitasking</a>, by allowing execution to be suspended and resumed.”</blockquote><p>Here, <strong>subroutine </strong>means a block of code(function or method) that performs a task, and <strong>non-preemptive</strong> means OS does not initiate context switch. The process itself yields control periodically or when idle or logically blocked. (This is known as <strong>cooperation.</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIs5q6_T23HkU9RqWDOA2w.png" /></figure><h3>Coroutines vs Threads</h3><ol><li>Coroutines are cooperatively multitasked. While threads are preemptively multitasked.</li><li>Coroutines provide concurrency but no parallelism — only one is executing at a time on a thread(just like subroutines/functions — they just pass the baton among each other). On the other hand, multiple threads can run simultaneously.</li><li>In the case of coroutines, there are no system calls, no need for mutexes &amp; semaphores, and no critical-section problems. Whereas for threads, the OS does context switching among them, and it needs to deal with critical section problems using mutexes &amp; semaphores.</li></ol><h3>Building Blocks of a Coroutine</h3><p>Let’s look at an example coroutine…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lTDgqAY6tzYn64Zlmu4Fw.png" /></figure><p>This is a coroutine to run a Room database query on a background thread(viz, <em>Dispatcher.IO</em>)</p><h4>Coroutine Dispatcher</h4><p>It defines what thread to use to run the coroutine. e.g.</p><ul><li>Main — main thread (run UI operations, update LiveData)</li><li>IO — background thread (disk read/write, networking)</li><li>Default — a shared pool of background threads(for CPU intensive tasks)</li></ul><h4>Coroutine Builder</h4><p>It creates and starts a coroutine.</p><ul><li><em>launch</em> — simply creates a coroutine and starts it. It does not return any result on completion.</li><li><em>async</em> — it starts a coroutine and returns a result after completion.</li><li><em>runBlocking</em> — it blocks the underlying thread. Generally used for writing unit tests.</li></ul><h4>Coroutine Scope</h4><p>It defines the lifecycle/lifetime of a coroutine. e.g.</p><ul><li>CoroutineScope — helps to create a custom scope. Coroutines started in this scope need to be canceled manually.</li><li><em>viewModelScope</em> — bound to the lifetime of a ViewModel. When the ViewModel clears, the coroutines in this scope will also cancel.</li><li><em>lifecycleScope</em> — bound to the lifetime of a LifecycleOwner (Fragment/Activity). When the Fragment/Activity destroys, the coroutines in this scope will also cancel.</li></ul><h3>Illustrative Examples</h3><ol><li>Do some tasks in the background</li></ol><pre>class DoggoRepository @Inject constructor(<br>    private val dao: DogsDao<br>) {</pre><pre>    fun saveInDB(list: List&lt;Dog&gt;) {<br>        <strong><em>CoroutineScope</em>(Dispatchers.IO).<em>launch </em>{<br>            dao.saveDoggos(dogs)<br>        }<br>    </strong>}<br>}</pre><p>Here, we are saving a list in the database. We created a coroutine using the <em>CoroutineScope</em>. We dispatched it on the background thread(<em>Dispatchers.IO</em>). Also, note that we have used <em>launch</em> because we don’t want to return any result after completing this operation.</p><p>2. Load data from a database</p><pre>class DoggoViewModel @Inject constructor(<br>    private val dao: DogsDao<br>) : ViewModel() {<br>    private val doggos = MutableLiveData&lt;List&lt;Dog&gt;&gt;()<br><br>    fun loadDoggos() {<br>        <strong><em>viewModelScope</em>.<em>launch </em>{<br>            doggos.<em>value </em>= dao.getDoggos()<br>        }<br>    </strong>}<br><br>    fun getDoggos(): LiveData&lt;List&lt;Dog&gt;&gt; = doggos<br>}</pre><p>Here, the coroutine is bound to <em>viewModelScope</em>’s lifetime. The coroutine will be canceled(if it is running) when the ViewModel clears. Since we do not wish to return anything after the execution, we used <em>launch</em> coroutine builder. Also, we didn’t pass any dispatcher because <em>viewModelScope</em> implicitly starts a coroutine on the Main thread.</p><p>Note that the function ‘<em>getDoggos()</em>’ is a suspending function. A <strong>suspend</strong> function executes a long-running task and forces the coroutine to wait for its completion. We’ll learn more about it in the future.</p><p>3. Do expensive calculations and return a result</p><pre>class DoggoViewModel @Inject constructor() : ViewModel() {<br>    private val fibonacciNumber = MutableLiveData&lt;BigInteger&gt;()<br><br>    fun loadNthFibonacciNumber(n: Int) {<br>        val fibonacciDeferred: <strong>Deferred</strong>&lt;BigInteger&gt; =<br>            <strong><em>CoroutineScope</em>(Dispatchers.Default).<em>async </em>{<br>                var a = BigInteger.<em>ONE<br>                </em>var b = BigInteger.<em>ONE<br>                repeat</em>(n) {<br>                    val sum = a + b<br>                    a = b<br>                    b = sum<br>                }<br>                return@async b<br>            }</strong><br>        <em>viewModelScope</em>.<em>launch </em>{<br>            fibonacciNumber.<em>value </em>= fibonacciDeferred.<strong>await()</strong><br>        }<strong><br>    </strong>}</pre><pre>    fun getFibonacciNumber(): LiveData&lt;BigInteger&gt; = fibonacciNumber<br>}</pre><p>Let’s dig into the concepts one by one. We are doing a time-taking calculation, e.g. calculating the 20,000th Fibonacci number. Thus we can do this in a coroutine. We created it using <em>CoroutineScope</em> and started it on a shared pool of background threads that perform CPU-intensive tasks(<em>Dispatchers.Default</em>).</p><p>Since we have to return the result after calculations, we used the <em>async</em> coroutine builder(<em>return@async b</em>). The <em>async</em> returns a <em>Deferred&lt;T&gt; </em>object. A <em>Deferred </em>encapsulates an operation that will be finished at some point in the future after its initialization.</p><p>After creating the <em>Deferred</em> object, we are calling <em>await()</em> on it. It means that we are waiting for its result and assigning it to the LiveData — <em>fibonacciNumber</em>. We can call <em>await()</em> only from a coroutine scope or a ‘suspend’ function. Thus, we are doing this operation in a coroutine started in <em>viewModelScope</em>.</p><p>To learn more about coroutines, check these out:</p><ul><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-2-the-suspend-function-95ebee74bfc8">Kotlin Coroutines(Part — 2): The ‘Suspend’ Function</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-3-coroutine-context-bd5543389190">Kotlin Coroutines(Part — 3): Coroutine Context</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-4-cancellation-811cd5a9813a">Kotlin Coroutines(Part — 4): Cancellation</a></li><li><a href="https://write.agrevolution.in/kotlin-coroutines-part-5-exception-handling-46e342d07f4c">Kotlin Coroutines(Part — 5): Exception Handling</a></li></ul><p>Thanks for reading! If you liked it, do hit the clap button! Keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56c88903129a" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/kotlin-coroutines-part-1-the-basics-56c88903129a">Kotlin Coroutines(Part — 1): The Basics</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leaks in Android Apps]]></title>
            <link>https://write.agrevolution.in/memory-leaks-in-android-apps-45a27c6ac35d?source=rss-83d35774f4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a27c6ac35d</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[leak-detection]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Aditi Katiyar]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 09:25:25 GMT</pubDate>
            <atom:updated>2021-06-18T09:25:25.587Z</atom:updated>
            <content:encoded><![CDATA[<h4>Causes of memory leaks while developing Android apps, how to detect and fix them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mOORxAoUeL6SpRnbh2YNQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@jibarofoto?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Luis Quintero</a> from <a href="https://www.pexels.com/photo/photo-of-gray-faucet-2339722/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>To increase the app’s performance, one must proactively check for memory leaks. They cause the app to slow down and sometimes force the OS to close it.</p><h4>What is a memory leak?</h4><p>A memory leak happens when the garbage collector allocates memory to an object but never deallocates it. The garbage collector thinks that the object is still needed because it is referenced by other objects, but those references should have been cleared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlqVCfmLHcU4Fnu5dfDOIA.png" /><figcaption><strong>obj1 </strong>will not be cleared until <strong>obj2 </strong>&amp; <strong>obj3 </strong>clear their references to <strong>obj1.</strong></figcaption></figure><p>If this continues to progress, the system might run out of heap memory and the app crashes.</p><h4>How to avoid memory leaks in Android?</h4><ul><li>Avoid keeping static references to Activities, Fragments, views, and <em>context</em>. Static objects live as long as the app is running and hence any static reference to a view (or <em>context</em>) will not be cleared on time.</li><li>Avoid using Activity’s <em>context</em> wherever possible. Try to use the application’s <em>context</em> instead(e.g. for creating Room database instances, etc.).</li><li>Avoid keeping static references to objects that use <em>context</em> to initialize themselves. e.g. One should not do something like this:</li></ul><pre>companion object {<br>    val database =  <br>        AppDB.getDB(MyApp.getInstance().applicationContext)<br>}</pre><ul><li>Avoid <em>binding</em> leaks by setting <em>binding = null</em> in the <em>onDestroyView()</em> lifecycle method. Android’s official documentation has mentioned <a href="https://developer.android.com/topic/libraries/view-binding#fragments">a cleaner way</a> to handle view bindings.</li><li>Pass <em>viewLifecycleOwner</em> instead of <em>this</em> while observing a LiveData object in a Fragment. This is because <em>viewLifecycleOwner</em> is tied to the fragment as long as it has its UI (<em>onCreateView()</em>, <em>onDestroyView()</em>). On the other hand, <em>this </em>is tied to the fragment’s overall lifecycle (<em>onCreate()</em>, <em>onDestroy()</em>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZl18Utddzkuu9PSeCJ2PQ.png" /></figure><pre>viewModel.getImagesLiveData().observe(<em>this</em>, Observer{<br>    // update views<br>})</pre><p>The above will cause a memory leak because we have passed <em>this</em> as the lifecycle owner. If the view is destroyed (<em>onDestroyView()</em> is called) but the fragment is not, (<em>onDestroy()</em> is not called), then any changes to the LiveData object are still observed and may cause a crash.</p><ul><li>Pass <em>viewLifecycleOwner.lifecycle</em> instead of <em>lifecycle</em> object in FragmentStateAdapter constructor, since we want to scope the adapter to the lifecycle of the fragment’s view and not the fragment.</li></ul><pre>viewPager.adapter =<br>    MyFragmnentStatePagerAdapter(<br>        lifecycle = <em>viewLifecycleOwner.lifecycle</em>,<br>        fragmentManager = childFragmentManager,<br>        .  .  .<br>    )</pre><ul><li>Avoid ViewPager-related leaks by doing the following in <em>onDestroyView(): </em>set <em>viewPager.adapter = null</em>, remove listeners set on tabs(if any), and detach TabLayoutMediator</li></ul><pre>override fun onDestroyView() {<br>    super.onDestroyView()<br>    binding.apply {<br>        viewPager.adapter = null<br>        tabLayout.removeOnTabSelectedListener(tabSelectedListener)<br>    }<br>    _binding = null<br>    tabLayoutMediator?.detach()<br>    tabLayoutMediator = null<br>}</pre><ul><li>Set RecyclerView adapter to null in <em>onDestroyView()</em> to prevent the adapter from holding a reference to the RecyclerView object.</li></ul><pre>override fun onDestroyView() {<br>    super.onDestroyView()<br>    binding.recyclerView.adapter = null<br>    .  .  .<br>}</pre><ul><li>Make sure to unregister all the listeners, broadcast receivers, etc. in the appropriate lifecycle method to prevent leaks. e.g. If a receiver is registered in <em>onViewCreated()</em>, then it must be unregistered in <em>onViewDestroyed()</em>.</li></ul><h4>How to detect memory leaks while developing the app?</h4><p><a href="https://square.github.io/leakcanary/">LeakCanary</a> is one of the best tools to detect memory leaks in Android apps. To use it, add the following dependency in your app’s build.gradle file:</p><pre>debugImplementation &#39;com.squareup.leakcanary:leakcanary-android:2.7&#39;</pre><p>Now run the app. Switch between fragments and activities, so as to stress the app and enforce the creation of a lot of objects. You will see notifications when there are any suspected leaks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*f0mjGqqvFFv-_FyqNapXCQ.png" /></figure><p>Click the notification to dump heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*69YBdezvuAwSOe9HAK74lQ.png" /></figure><p>After a few seconds, you will see another notification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*ACLF9W0b0Jc67sk-72PkAQ.png" /></figure><p>Click this notification. It will open the list of leaks as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*HMKjdyM-LN_Qft6Pa2PRxw.png" /></figure><p>Right now, there is just one type of leak. The <em>_binding</em> of ListFragment seems to be leaking. Let’s open this and check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*3kqCtLcaZsyIgc014giKOw.png" /></figure><p>There is 1 distinct leak that has occurred 4 times. Scroll down the leak trace to check the exact point where the leak happened. (You can also print the leak trace to Logcat.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*7aNEdkOZjKRZ_PBGeEnjxw.png" /></figure><p>The ‘Leaking: YES’ confirms the exact object that was leaking. Here it says :</p><blockquote>ObjectWatcher was watching this because com.example.myApplication.ListFragment received Fragment#onDestroyView() callback (references to its views should be cleared to prevent leaks)</blockquote><p>This clearly says that the <em>_binding</em> object should have been cleared in <em>onDestroyView()</em>. Doing <em>‘_binding = null’</em> in <em>onDestroyView() </em>will fix the leak!</p><p>LeakCanary is an easy-to-use tool. You can also use Android Studio’s <a href="https://developer.android.com/studio/profile/memory-profiler">memory profiler</a> to track memory usage and leaks. It gives more insight into how our app is affecting the system’s memory.</p><p>Thanks for reading! If you liked it, do hit the clap button! Keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a27c6ac35d" width="1" height="1" alt=""><hr><p><a href="https://write.agrevolution.in/memory-leaks-in-android-apps-45a27c6ac35d">Memory Leaks in Android Apps</a> was originally published in <a href="https://write.agrevolution.in/">DeHaat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>