<?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 Dheeraj Andra on Medium]]></title>
        <description><![CDATA[Stories by Dheeraj Andra on Medium]]></description>
        <link>https://medium.com/@Asdheeraj?source=rss-e9fc16195c5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z2iMpk-IJKD8CGoQpsmk0A.jpeg</url>
            <title>Stories by Dheeraj Andra on Medium</title>
            <link>https://medium.com/@Asdheeraj?source=rss-e9fc16195c5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:42:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Asdheeraj/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[FAQs for Google SWE Interview]]></title>
            <link>https://medium.com/@Asdheeraj/faqs-for-google-swe-interview-4668d4c77fba?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4668d4c77fba</guid>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[faang]]></category>
            <category><![CDATA[google-interview]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 19:27:38 GMT</pubDate>
            <atom:updated>2023-07-05T19:27:38.235Z</atom:updated>
            <content:encoded><![CDATA[<p>I just had my cup of coffee and was getting ready for my work day. It was a normal Tuesday Morning until, I got a phone call!. The Incoming call seemed to be an overseas number. I hesitantly picked up the call and said “Hello?!”</p><p>The voice from the other end confirmed my name and said “Hi Dheeraj! Im calling on behalf of Google..”</p><p>I was stunned and took a few seconds to be normal. It was a day I was waiting all my professional life ever since I decided to progress my career as a Software Engineer!</p><p>Hello and Welcome to my blog on “Prep Tips for Google SWE Interview”. I hope this blog will help to share some of the tips I learnt along this journey. So, let’s get started. I will also be sharing some references towards the end of this article.</p><p>Please be sure to checkout the FAQs section at the end (These are some of the questions I had during this process)</p><p>Please note that my experience is more inclined towards the role of “Software Engineer”.</p><h3>Google Interview Process — A Brief</h3><p>Google’s Interview process is mainly divided into three segments<br>Recruiter Screen, Phone Screen and Onsite</p><h4>Recruiter Screen</h4><p>Once your resume is shortlisted, one of the Google Recruiters will connect with you to understand a brief about yourself and your experience. If the recruiter finds your profile matching the role description, you would be informed and guided about your Phone Screen round.</p><p><em>Google Recruiters are one of the best in the business. They understand the pressure that might come with interviewing at Google and they will be there for you throughout the journey.</em></p><h4>Phone Screen</h4><p>This is in general a coding round that is scheduled for like 45–60 mins. Mostly, this round will be a coding round focused around Data Structures and Algorithms.</p><p>Once your Phone Screen is completed and your feedback is positive, your recruiter will forward your profile to Onsite Rounds.</p><h4>OnSite Round</h4><p>Google Interview generally has five onsite rounds. The split of these onsite rounds will again be dependent on the role that you are interviewing. This will be well explained by your recruiter during your discussions. Please pay attention. Your recruiter is your best Point of contact during this journey.</p><p>The General Split that I have observed:</p><ul><li>3 Coding Rounds (DS Algo) + 1 System Design + 1 Googlyness &amp; Leadership Round</li><li>2 Coding Rounds (DS Algo) + 1 System Design + 1 Domain Specific (System Design) + 1 Googlyness &amp; Leadership Round</li><li>2 Coding Rounds (DS Algo) + 2Domain Specific (System Design) + 1 Googlyness &amp; Leadership Round</li></ul><p>Now, Im not going too much into how these rounds are scheduled.. what level of questions will be asked etc etc. Because it might differ from role to role that you are interviewing, and your recruiter is your best help in this case.</p><p>My main focus in this article is to help you with the kind of questions that you might get during this process. Please refer the following FAQ section for the same.</p><p><strong><em>FAQs</em></strong></p><p><strong><em>Q 1: What is the ideal time to prepare DS Algo for a working professional?</em></strong><em><br>A: Depends. In my view, if you have an idea of basic DS Algo and if done dedicatedly, 3 months. (8–10 hrs per week)<br>If completely new, 6–12months. Again, this is subjective to the individual.</em></p><p><em>Q2: How can I become better at Ds Algo?<br>A: Practice. No other way, Sorry.</em></p><p>Q3: If I’m just getting started with Ds Algo, what’s your tip?<br>A: Get started with understanding the Data Structure implementation and the Big O notation.</p><p><strong><em>Q 4: How many days until my Recruiter finds my profile matching to the role to the Phone Screen?</em></strong><em><br>A: The Recruiter leaves this decision to us. An ideal time would be between 2 -4weeks.</em></p><p><em>Q 5: I haven’t prepared DS Algo for a long time / I’m yet to start with DS Algo.</em></p><p>A: Be focused on the preparation. Keep it simple. Try to be consistent. These are words easily said than done. But completely worth it. Start your prep. Dont wait for the right time!</p><p>Ive just listed down a few common 5 questions. If you have more, please let me know in the comments below.</p><p>Lets connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4668d4c77fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the role of ViewModel in Orientation Changes-Android]]></title>
            <link>https://medium.com/@Asdheeraj/understanding-the-role-of-viewmodel-in-orientation-changes-android-ac08b7948620?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac08b7948620</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 07:19:30 GMT</pubDate>
            <atom:updated>2020-04-27T07:23:18.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA2P5A-7ccGw-hS2F1Gk1A.png" /></figure><p>The introduction of ViewModel in the Android Architecture components has helped in handling the orientation changes while using the MVVM android design pattern.</p><p>I have written a detailed explanation of the flow of how the ViewModel helps in handling the orientation changes in Android on the EIDK platform.</p><p>Please follow <a href="https://eidk.org/Understanding-the-role-of-ViewModel-in-Orientation-Changes-Android.html">the link below</a> for a detailed explanation.</p><p><a href="https://eidk.org/Understanding-the-role-of-ViewModel-in-Orientation-Changes-Android.html">Understanding ViewModel in Orientation Changes-Android</a></p><p>Please follow <a href="https://github.com/asdheeraj/ViewModelOrientationChange">this link</a> for the project GitHub link used in the article.</p><p><a href="https://github.com/asdheeraj/ViewModelOrientationChange">asdheeraj/ViewModelOrientationChange</a></p><h4>Flow Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTQpqd-nw_X4GFH94EsK2Q.png" /></figure><p>I hope that the most important feature of the ViewModel in the MVVM architecture components is now understood!</p><p>Thank you so much for your time!</p><p>If you find this article helpful, please share it with the community!</p><p><strong>Also, Let’s connect on</strong> <a href="https://twitter.com/AndraDheeraj"><strong>Twitter</strong></a><strong>,</strong> <a href="https://www.linkedin.com/in/dheerajsree/"><strong>Linkedin</strong></a><strong>,</strong> <strong>and</strong> <a href="https://github.com/asdheeraj"><strong>Github</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac08b7948620" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Sealed classes in Kotlin]]></title>
            <link>https://medium.com/@Asdheeraj/working-with-sealed-classes-in-kotlin-24f101b1d4de?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f101b1d4de</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 03:58:43 GMT</pubDate>
            <atom:updated>2020-03-16T03:58:43.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VAAkZY1_5lvvzt7Bm7UtQ.png" /></figure><p>As developers, most often we try to use Enums for storing different possibilities of the same data type. Such as:</p><pre>enum class Color {<br>    RED, GREEN, BLUE<br>}</pre><p>But do we know how can Sealed classes help us in this regard? How are they better than Enums as well as Abstract classes? How can we use Sealed classes the right way?</p><p>All answers to these questions can be found in <a href="https://blog.mindorks.com/learn-kotlin-sealed-classes">this</a> article:</p><p><a href="https://blog.mindorks.com/learn-kotlin-sealed-classes">Working with Kotlin Sealed Classes</a></p><p>I hope <a href="https://blog.mindorks.com/learn-kotlin-sealed-classes">this</a> article helped you understand the usage of Sealed classes in a better and right way.</p><p>Thank you so much for your time.</p><p>You can also check out my articles on <a href="https://medium.com/mindorks/dagger-android-part-1-31ede7ad1998">Dagger for Android</a>, <a href="https://medium.com/mindorks/work-manager-in-android-9cdb66c9a1df">Work Manager in Android</a>, <a href="https://medium.com/mindorks/realm-with-android-acf50ea68ece">Realm with Android</a></p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f101b1d4de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data classes in Kotlin]]></title>
            <link>https://medium.com/mindorks/data-classes-in-kotlin-369e95c2f0ea?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/369e95c2f0ea</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 12:48:42 GMT</pubDate>
            <atom:updated>2019-11-01T12:48:42.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSaWlWIotlYp-k_iOT80zA.png" /></figure><p>Still developing Android applications in Java? It’s high time to try out Kotlin. Many Android Developers have experienced the benefit of moving to Kotlin from Java and now Kotlin has become the top choice for Android Developers.</p><p>In this blog, we are going to discuss the concept of Data classes in Kotlin.</p><h4>What is a data class in Kotlin?</h4><p>A data class is something that holds the data for us. It doesn’t hold any other functionality in it. When we developed Android applications in Java, we used to create PoJo classes for the same which looked something like this:</p><pre><strong>public</strong> <strong>class</strong> <strong>Developer</strong> {<br><br>    <strong>private</strong> String name;<br>    <strong>private</strong> <strong>int</strong> age;<br><br>    <strong>public</strong> <strong>Developer</strong>(String name, <strong>int</strong> age) {<br>        <strong>this</strong>.name = name;<br>        <strong>this</strong>.age = age;<br>    }<br><br>    <strong>public</strong> String <strong>getName</strong>() {<br>        <strong>return</strong> name;<br>    }<br><br>    <strong>public</strong> <strong>void</strong> <strong>setName</strong>(String name) {<br>        <strong>this</strong>.name = name;<br>    }<br><br>    <strong>public</strong> <strong>int</strong> <strong>getAge</strong>() {<br>        <strong>return</strong> age;<br>    }<br><br>    <strong>public</strong> <strong>void</strong> <strong>setAge</strong>(<strong>int</strong> age) {<br>        <strong>this</strong>.age = age;<br>    }<br><br>    <strong>@Override</strong><br>    <strong>public</strong> <strong>boolean</strong> <strong>equals</strong>(Object o) {<br>        <strong>if</strong> (<strong>this</strong> == o) <strong>return</strong> <strong>true</strong>;<br>        <strong>if</strong> (o == <strong>null</strong> || getClass() != o.getClass()) <strong>return</strong> <strong>false</strong>;<br><br>        Developer developer = (Developer) o;<br><br>        <strong>if</strong> (age != developer.age) <strong>return</strong> <strong>false</strong>;<br>        <strong>return</strong> name != <strong>null</strong> ? name.equals(developer.name) : developer.name == <strong>null</strong>;<br><br>    }<br><br>    <strong>@Override</strong><br>    <strong>public</strong> <strong>int</strong> <strong>hashCode</strong>() {<br>        <strong>int</strong> result = name != <strong>null</strong> ? name.hashCode() : 0;<br>        result = 31 * result + age;<br>        <strong>return</strong> result;<br>    }<br><br>    <strong>@Override</strong><br>    <strong>public</strong> String <strong>toString</strong>() {<br>        <strong>return</strong> &quot;Developer{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, age=&quot; + age +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>Why should we write a lot of boilerplate code in a class that only holds some data for us?</p><p>Now, in Kotlin all we need to is:</p><pre><strong>data</strong> <strong>class</strong> <strong>Developer</strong>(<strong>val</strong> name: String, <strong>val</strong> age: Int)</pre><p>Looks clean and concise right? The lesser code, the lesser bugs it can produce and hence Kotlin is preferred over Java by Android Developers.</p><p>When a class is marked as data class in kotlin, the compiler automatically creates the following:</p><ul><li>getters and setters for the constructor parameters</li><li>hashCode()</li><li>equals()</li><li>toString()</li><li>copy()</li></ul><p>But for a class to be a data class in Kotlin, the following conditions are to be fulfilled:</p><ul><li>The primary constructor needs to have at least one parameter.</li><li>All primary constructor parameters need to be marked as val or var</li><li>Data classes cannot be abstract, open, sealed or inner.</li></ul><p>If there are explicit implementations of equals(), hashCode() or toString() in the data class body or final implementations in a superclass, then these functions are not generated, and the existing implementations are used.</p><p>I hope this article has been of some use.</p><p>You can also check out my articles on <a href="https://medium.com/mindorks/dagger-android-part-1-31ede7ad1998">Dagger for Android</a>, <a href="https://medium.com/mindorks/work-manager-in-android-9cdb66c9a1df">Work Manager in Android</a></p><p>Thank you so much for your time.</p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=369e95c2f0ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/data-classes-in-kotlin-369e95c2f0ea">Data classes in Kotlin</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[The Notification Limit per app in Android]]></title>
            <link>https://medium.com/mindorks/the-notification-limit-per-app-in-android-94af69a6862c?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/94af69a6862c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 13:49:45 GMT</pubDate>
            <atom:updated>2019-08-15T13:53:36.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lioi_Uv8qvXntSB5QXxSMw.png" /></figure><p>Have you ever wondered if there is any notification limit per application in Android. I never thought there was one until I actually tried it out. Yes, there is a limit of notifications that can be posted per app. The interesting thing was the number is not fixed and can be controlled by the device Manufacturer. From my observation, a Google Pixel 3A phone had limited to 25 notifications where as a OnePlus 6T and a Samsung device had limited the notifications to 50.</p><p>Where has Android actually specified that there is a limit for notifications per app. Well, sadly after going through all the official documentation I couldn’t find anything wrt the limit of number of notifications that can be posted.</p><p>But there was a good <a href="https://stackoverflow.com/questions/33364368/android-system-notification-limit-per-app">stackOverflow post</a> that I have come across which has mentioned that they have come up with an observation.</p><p><a href="https://stackoverflow.com/questions/33364368/android-system-notification-limit-per-app">android system notification limit per app</a></p><p>If we carefully observe the <a href="https://android.googlesource.com/platform/frameworks/base/+/0e57464d905037dfb269a221963d91f65b288288/services/java/com/android/server/NotificationManagerService.java">NotificationManagerService.java</a> source code, we can see a variable MAX_PACKAGE_COUNT declared to be 50.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0T59hHwP2Zd35Sliljo9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmttPS0pK_MSiOG3BZz84Q.png" /></figure><p>And inside the code, it checks if the count is greater than the MAX_PACKAGE_NOTIFICATIONS, it has a message saying that “Package has . already posted max toasts. Not showing more!”</p><p>This is the reason we get limited by the amount of notifications that are posted per app.</p><p>I request you to give it a try and check out the max number of notifications that can be posted by an app. You can use a simple for loop for this and at one point the notifications stop being posted.</p><p>Now, whats the solution for this? How come we can let the user know that the maximum number of notifications are reached. How can we continue posting notifications by applying a logic so that the user does not miss the recent notifications?</p><p>Well, let’s find that out in this article.</p><p>We will be creating a sample app. We will be scheduling notifications for every second. We will be keeping a track of also the active notifications in the Notifications bar.</p><p>So, let’s get started.</p><p>The project repo can be found on <a href="https://github.com/asdheeraj/NotificationLimit">this</a> link:</p><p><a href="https://github.com/asdheeraj/NotificationLimit">asdheeraj/NotificationLimit</a></p><p>Let’s create a new project in Android Studio with a Blank Activity.</p><p>Now, in the on-create function, let’s create a Notification channel, since starting Android O we can’t display a Notification without a channel.</p><pre>val notificationManager =<br>    this.getSystemService(Context.<em>NOTIFICATION_SERVICE</em>) as NotificationManager<br>//If the Sdk version is greater than &#39;O&#39;, configure a Notification channel<br>if (Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>O</em>) {<br>    val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID,<br>        NOTIFICATION_CHANNEL_NAME, NotificationManager.<em>IMPORTANCE_DEFAULT</em>)<br>    // Configure the notification channel<br>    <em>with</em>(notificationChannel) <strong>{<br>        </strong><em>description </em>= NOTIFICATION_CHANNEL_DESCRIPTION<br>        enableLights(true)<br>        <em>vibrationPattern </em>= <em>longArrayOf</em>(0, 1000, 500, 1000)<br>        enableVibration(true)<br>        notificationManager.createNotificationChannel(this)<br>    <strong>}<br></strong>}</pre><p>Now, let’s create a function which checks for the active notifications and notifies the user:</p><pre><em>/**<br> * Checks for the Maximum notifications and Notify the user<br> * </em><strong><em>@param </em></strong><em>notificationManager The NotificationManager instance<br> */<br></em>private fun checkAndScheduleNotifications(notificationManager: NotificationManager) </pre><p>You can check in this function that we get the active notifications from notification manager or the NotificationListenerService.</p><h4>What are activeNotifications?</h4><p>Active Notifications are an array of StatusBarNotifications for the respective app which are present in the Status bar.Now we have two ways to get this:</p><p><a href="https://developer.android.com/reference/android/app/NotificationManager.html#getActiveNotifications()">NotificationManager.getActiveNotifications() (for API≥23)</a></p><p><a href="https://developer.android.com/reference/android/service/notification/NotificationListenerService.html#getActiveNotifications(java.lang.String[])">NotificationListenerService.getNotifications() (for API(≤22))</a></p><h4>Note:</h4><p>Please ensure that the Notification access in the Settings is selected for the respective app(if NotificationListenerService is used). Otherwise accessing the StatusBarNotifications data is not possible</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqQqkhJoX937tLAvUhdumA.png" /></figure><p>So what we are doing here is:</p><p>Firstly, we are sorting the activeNotifications based on the postTime :</p><pre>Collections.sort(currentNotifications, compareNotificationByPostTime)</pre><p>The compareNotificationByPostTime is our custom comparator that sorts the array by the notification post time</p><pre>private val compareNotificationByPostTime = <em>Comparator</em>&lt;StatusBarNotification&gt; <strong>{ </strong>o1, o2 <strong>-&gt;<br>    </strong>return@Comparator (o1.<em>postTime</em>).compareTo(o2.<em>postTime</em>)<br><strong>}</strong></pre><p>Here is the logic where we check for maximum notification count and update the StatusBar notifications</p><pre>when (currentNotifications.size) {<br>    in NOTIFICATION_START_LIMIT..getMaxNotificationsCount() -&gt; {<br>        notifyUser(notificationManager)<br>    }<br>    else -&gt; {<br>        Collections.sort(currentNotifications, compareNotificationByPostTime)<br>                if (currentNotifications.<em>isNotEmpty</em>()) {<br>                    notificationManager.cancel(currentNotifications.<em>first</em>().<em>tag</em>,<br>                        currentNotifications.<em>first</em>().<em>id</em>)<br>                    notifyUser(notificationManager)<br>                }<br>    }<br>}</pre><p>We are checking if the activeNotifications are in the limit required. If not, we are cancelling the oldest posted notification form the status bar notification and then notifying the user with the newest one.</p><p>So, this way even the user does not clear the notifications for a certain period of time, he can still be updated with the latest notifications even if there is a limit of maximum notifications per app to be posted.</p><p>I hope this article has been of some use.</p><p>You can also check out my articles on <a href="https://medium.com/mindorks/dagger-android-part-1-31ede7ad1998">Dagger for Android</a>, <a href="https://medium.com/mindorks/work-manager-in-android-9cdb66c9a1df">Work Manager in Android</a></p><p>Thank you so much for your time.</p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94af69a6862c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/the-notification-limit-per-app-in-android-94af69a6862c">The Notification Limit per app in Android</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[Working With WorkManager in Android Like A Pro]]></title>
            <link>https://medium.com/mindorks/work-manager-in-android-9cdb66c9a1df?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cdb66c9a1df</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[workmanager]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Wed, 01 May 2019 07:31:22 GMT</pubDate>
            <atom:updated>2019-05-01T07:34:47.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_zo1GGLwekYWmlzhlv3yg.png" /></figure><p>How can we schedule our application tasks at a particular time or periodically? How can we add constraints to our scheduled task like network availability(only Wifi some times) or if the device is charging? We see such tasks occurring in our day to day applications like WhatsApp and PlayStore App updates. Can we chain up such tasks together? We have a solution for all these questions and many more in Android Development.</p><h4><a href="https://developer.android.com/topic/libraries/architecture/workmanager"><strong>Work Manager</strong></a></h4><p>Welcome to the Android-Work Manager blog.</p><p>Work Manager is part of <a href="https://developer.android.com/topic/libraries/architecture">Architecture components</a> of the <a href="https://developer.android.com/jetpack">Android Jetpack Library</a>.</p><p>So let’s discuss Work Manager and its use in background processing in this blog.</p><p>We have a lot of ways to do background processing in Android, like AsyncTasks, Loaders, Alarm Managers, etc., Which one to use when? How can we come to a decision on the same?</p><p>For more information, please refer to <a href="https://developer.android.com/guide/background/">background processing guide</a></p><p>As an Android Developer, we should have an idea of the latest optimizations Android is coming up with its newer versions of OS being released for better performance. Also, we cannot guarantee every android device being used in the market contains the latest version of the Android OS installed. So, we should think about backward compatibility to reach the maximum number of devices that are present in the market(at least a min SDK of KitKat).</p><p>So how do we categorize our work that needs to be scheduled based on its importance?</p><p>Let’s say our work is to open a contacts screen by clicking on the Contacts button. This is something that is only related to the UI part. Hence the main thread or the UI thread is enough to perform this piece of work. We don’t need this to be done when our device is in doze state. This is an example of a <strong>Foreground Service. </strong>It’s a guaranteed execution and it needs to be done immediately.</p><p>Now, let’s say we have to perform a task but it need not be immediate. Like you want to set a reminder for the day after tomorrow at 8 pm. Now, this reminder will occur nearly after 48 hrs. So the device can be in a doze mode or alive during this period. We have a handful of APIs to perform these tasks. Like Job Schedulers, Firebase Job dispatchers, or Alarm manager with Broadcast receivers in the previous versions.</p><p>Now, what if we have a functionality that needs all the properties of these APIs. We tend to come with a combination of all the APIs discussed. That’s a lot of APIs to be used for in a single application. This is where <strong>WorkManager</strong> comes into the picture.</p><h4>BackWard Compatible</h4><p>WorkManager is Backward compatible up to API 14 -Uses JobScheduler on devices with API 23+, Uses a combination of BroadcastReceiver + AlarmManager on devices with API 14–22</p><p>WorkManager is intended for tasks that are <strong>deferrable</strong> — that is, not required to run immediately — and required to <strong>run reliably</strong> even if the app exits or the device restarts. For example:</p><ul><li>Sending logs or analytics to backend services</li><li>Backing up user data with Server on a Periodic basis (Eg: WhatsApp, Google, etc.,)</li></ul><h4><strong>Constraint Aware</strong></h4><p>WorkManager is constraint aware. In our day to day usage, we see our phone getting the latest software updates and we are requested to keep our devices in charging mode for these updates to happen as it may take time and insufficient charge can lead to improper installation of software. Sometimes, we see our apps getting updated as soon as we connect our phones to our power adapters. These kinds of tasks are constraint aware.</p><pre>// Create a Constraints object that defines when the task should run<br>val constraints = Constraints.Builder()<br>        .setRequiresDeviceIdle(true)<br>        .setRequiresCharging(true)<br>        .build()<br><br>// ...then create a OneTimeWorkRequest that uses those constraints<br>val compressionWork = OneTimeWorkRequestBuilder&lt;CompressWorker&gt;()<br>        .setConstraints(constraints)<br>        .build()</pre><h4>Accepts Queries</h4><p>WorkManager is Queryable.<strong> </strong>A work that is handed off to the system by the WorkManager can be in a Blocked State, Running State or a Cancelled State. We can get the state of the work by passing the id of the Work like below:</p><pre>WorkManager.getInstance().getWorkInfoByIdLiveData(uploadWorkRequest.id)<br>        .observe(lifecycleOwner, Observer { workInfo -&gt;<br>            if (workInfo != null &amp;&amp; workInfo.state == WorkInfo.State.SUCCEEDED) {<br>                progressbar.visibility  = View.GONE<br>            }<br>        })</pre><p>By doing this, we can improve the UX by displaying a progress bar while the task is being executed by the work manager.</p><h4>Chainable</h4><p>WorkManager is Chainable.<strong> </strong>Let’s say we have a series of works that are dependent on each other, we can chain them up with Work Manager. You can also specify the order in which the works that are chained should be done.</p><p>Eg:</p><pre>WorkManager.getInstance()<br>    // Candidates to run in parallel<br>    .beginWith(listOf(work 1, work 2, work 3))<br>    // Dependent work (only runs after all previous work in chain)<br>    .then(work 4)<br>    .then(work 5)<br>    // Don&#39;t forget to enqueue()<br>    .enqueue()</pre><p>Let’s say we want to upload photos to the server. For this task to be done, let’s say we want to compress the images first and then upload it. These tasks need to be done on a background thread as they are time taking tasks and it is evident in this case that they are dependent on each other. We can chain up these tasks by using the Work Manager.</p><p>In the above code snippet, work 1, work 2 and work 3 can be referred to as three different images that are extracted in parallel since they are a part of beginWith(). work 4 can be referred for compress and then work 5 can be upload. This way we can chain up our tasks.</p><p>WorkManager can be used to perform a unique task(<a href="https://developer.android.com/reference/androidx/work/OneTimeWorkRequest">OneTimeWorkRequest</a>) or a recurring task(<a href="https://developer.android.com/reference/androidx/work/PeriodicWorkRequest">PeriodicWorkRequest</a>) based on the requirement.</p><p><em>A </em><a href="https://developer.android.com/reference/androidx/work/PeriodicWorkRequest"><em>PeriodicWorkRequest</em></a><em> minimum period length is </em><strong><em>15 minutes</em></strong></p><p>In order to execute a OneTimeWorkRequest or the PeriodicWorkRequest, we have to pass the work to these requests which are our <a href="https://developer.android.com/reference/androidx/work/Worker">Worker</a> class. This is where our business logic is written in the doWork() method:</p><pre>class UploadWorker(appContext: Context, workerParams: WorkerParameters)<br>    : Worker(appContext, workerParams) {<br><br>    override fun doWork(): Result {<br>        // Do the work here--in this case, upload the images.<br><br>        uploadImages()<br><br>        // Indicate whether the task finished successfully with the Result<br>        return Result.success()<br>    }<br>}</pre><p>The doWork() method runs on the background thread. We can see here a <strong>success</strong> result is returned once the uploadImages is successful. The other two enum values for the return type are a <strong>failure</strong> and <strong>retry. </strong>Return types success and failure are fairly obvious, but what does retry do here? Let’s say we are performing a task with a Work Manager with a constraint that is network connected. If the network get’s disconnected in the midst of the work being done, we can retry the task.</p><h4>Inputs and Outputs</h4><p>Not just this, we can create <a href="https://developer.android.com/reference/androidx/work/Data">data</a> as inputs and get outputs as <a href="https://developer.android.com/reference/androidx/work/Data">data</a> with respect to WorkManager requests. The inputs and outputs are stored as key-value pairs in the <a href="https://developer.android.com/reference/androidx/work/Data">Data</a> object.</p><p>So, how do we create a <a href="https://developer.android.com/reference/androidx/work/Data">data</a> object? Let’s create a simple map in kotlin and convert it into a workData so that it gives a <a href="https://developer.android.com/reference/androidx/work/Data">Data</a> object</p><pre>val inputData: Data = mapOf(<br>      &quot;<strong>image_name</strong>&quot; to &quot;android.png&quot;<br>).toWorkData()</pre><pre>val compressionWork = OneTimeWorkRequestBuilder&lt;CompressWorker&gt;()<br>        .<strong>setInputData</strong>(inputData)<br>        .build()</pre><p>Now, where can we retrieve this data? It can be done in the overridden doWork method in our Worker class</p><pre>class CompressWorker(appContext: Context, workerParams: WorkerParameters)<br>    : Worker(appContext, workerParams) {<br><br>    <strong>override fun doWork()</strong>: Result {</pre><pre><strong>        val inputData: Data = getInputData()<br></strong>        val imageName =                                                                 <strong>inputData</strong>.getString(&quot;<strong>image_name</strong>&quot;,&quot;default_val&quot;)<strong><br>        </strong>val images: Map<strong> = </strong>compressImages(imageName)</pre><pre>        return Result.success()<br>    }<br>}</pre><pre>fun compressImages(imageName: String) : Map{<br>//returns a map of image mapped to its size<br>}</pre><p>Now, we see that the compressImages is returning a map of images mapped to their respective sizes. Let’s say we need this data. We can set the output from our worker thread as a <a href="https://developer.android.com/reference/androidx/work/Data">Data</a> object.</p><pre>class CompressWorker(appContext: Context, workerParams: WorkerParameters)<br>    : Worker(appContext, workerParams) {<br><br>    override fun doWork(): Result {</pre><pre>val inputData: Data = getInputData()<strong><br></strong>        val imageName =                                                                 inputData.getString(&quot;image_name&quot;,&quot;default_val&quot;)<strong><br>        </strong>val compressedImages: <strong>Map = </strong>compressImages(imageName)<br>        <strong>val outputData: Data = compressedImages.toWorkData()<br>        setOutputData(outputData)</strong><br>        return Result.success()<br>    }<br>}</pre><pre><strong>fun compressImages(imageName: String) : Map</strong>{<br>//returns a map of image mapped to its size<br>}</pre><p>If we are using a chain of work requests here, the key observation is that the output of a worker will become input for its child workRequests.</p><p>Let’s say we use a UploadWorker after the CompressWorker, the compressedImages that is executed in the CompressWorker can be an input to the UploadWorker. It can be retrieved similarly in the doWork method of the UploadWorker class.</p><p>This works fine if we have only one worker request chained with another work request. What if we have multiple work requests(running parallel) chained with another work request that needs input from all these parallelly running work requests like</p><pre>WorkManager.getInstance()<br>    // Candidates to run in parallel<br>    .beginWith(listOf(work 1, work 2, work 3))<br>    // Dependent work (only runs after all previous work in chain)<br>    .then(work 4)<br>    .then(work 5)<br>    // Don&#39;t forget to enqueue()<br>    .enqueue()</pre><p>What if the input for work 4 should be the combined output of work 1, work 2 and work 3? <a href="https://developer.android.com/reference/androidx/work/InputMerger">InputMerger</a> to the rescue.</p><h4>InputMerger</h4><p><a href="https://developer.android.com/reference/androidx/work/InputMerger">InputMerger</a> is a class that combines data from multiple sources into one <a href="https://developer.android.com/reference/androidx/work/Data">Data</a> object. There are two different types of InputMergers provided by WorkManager:</p><p><a href="https://developer.android.com/reference/androidx/work/OverwritingInputMerger.html">OverwritingInputMerger</a> (default) attempts to add all keys from all inputs to the output. In case of conflicts, it overwrites the previously-set keys.</p><p><a href="https://developer.android.com/reference/androidx/work/ArrayCreatingInputMerger.html">ArrayCreatingInputMerger</a> attempts to merge the inputs, creating arrays when necessary.</p><h4><strong>Important note:</strong></h4><p>There might be instances where we get outputs containing similar keys. So, we must be cautious in choosing our Inputmergers. If we want to override the key values, we can go for OverwritingInputMerger. If we want to save all the instances of the respective Key, we have to use ArrayCreatingInputMerger. It creates an array of values(if the values for a key are more than one) for the respective key.</p><h4><strong>Exception-Example case study for ArrayCreatingInputMerger:</strong></h4><p>Let’s say we have a key, “age”. One work request has value 30(Int) in it for this key. Another work request has value “three days”(String) in it for the same key. Can the ArrayCreatingInputManager merger these values and create an array for the key “age”? No. It gives an exception. So, it is expected that the datatypes of the values for similar keys should be the same.</p><h4>How to use InputMerger</h4><pre>val compress: OneTimeWorkRequest = OneTimeWorkRequestBuilder&lt;CompressWorker&gt;()<br>    <strong>.setInputMerger(ArrayCreatingInputMerger::class)</strong><br>    .setConstraints(constraints)<br>    .build()</pre><pre>WorkManager.getInstance()<br>    .beginWith(compress)<br>    .then(upload)<br>    .enqueue()</pre><p>Work Manager can cancel the unwanted tasks or tasks that are scheduled by mistake. All that we need to do is to send the task id to cancelWorkById() method :</p><pre>WorkManager.cancelWorkById(workRequest.id)</pre><h3>The Tag Support</h3><p>The ids that we are referring to here are auto-generated and generally large numbers that are not easily readable by humans. Let’s say we have to log them we are unsure whether we are logging the correct workRequest Id. To overcome this issue, each work request can have zero or more tags. We can query or delete our work requests by using these tags.</p><pre>// ...then create a OneTimeWorkRequest with a tag<br>val compressionWork = OneTimeWorkRequestBuilder&lt;CompressWorker&gt;()<br>        .addTag(&quot;image_1&quot;)<br>        .build()<br>workmanager.enqueue(compressionWork)</pre><p>Now, if we want to see the status of all the works that are associated with a given tag, we can just use</p><pre>val statusLiveData:LiveData&lt;List&lt;WorkStatus&gt;&gt; = workManager.getStatusesByTag(&quot;image_1&quot;)</pre><p>The above statement returns a LiveData&lt;List&lt;WorkStatus&gt;&gt; as more than one work request can be associated with a single tag. We can use this result to get the statuses like</p><pre>statusLiveData.observe(lifeCycleOwner, Observer { statuses-&gt;<br>    //...<br>})</pre><p>Similarly, we can use the tags to cancel the work like:</p><pre>workManager.cancelAllWorkByTag(&quot;image_1&quot;)</pre><h3>Existing Work-Keep it unique or Add Operations with Keep, Replace and Append</h3><h4>Keep, Replace and Append</h4><p>These three properties add advantage to using Work Manager.</p><h4>Keep</h4><p>Let’s say we have a work request with tag “image_1” that is already enqueued with the WorkManager.</p><p>Let’s say we define this work request to upload a particular image. And if by mistake, we click on upload the same image, this property helps us in not repeating the task.</p><pre>workManager.beginUniqueWork(&quot;upload&quot;, <strong>KEEP</strong>, uploadRequest).enqueue()</pre><p>So, if there is work already with “upload” ongoing, it will keep that request. If there isn’t one, it will enqueue this particular request.</p><h4><strong>Replace</strong></h4><pre>workManager.beginUniqueWork(&quot;upload&quot;, <strong>REPLACE</strong>, uploadRequest).enqueue()</pre><p>This will replace any ongoing work with the name “upload” and replaces it by enqueuing this particular work.</p><h4>Append</h4><pre>workManager.beginUniqueWork(&quot;upload&quot;, <strong>APPEND</strong>, uploadRequest).enqueue()</pre><p>This helps in appending the respective work request to an already existing unique work request with the name “upload”(if it exists)</p><p><strong>Note: </strong>Please be careful when you add the constraints to the work requests in a chain of work requests. Each and every work request that is being chained may not need the same constraints. For example, if our work request contains image upload and we are chaining compress image and upload image work requests together, compressing an image may have constraints related to storage and uploading image can have a constraint with respect to the network connection. So, add the constraints accordingly.</p><h3>References</h3><p><a href="https://developer.android.com/topic/libraries/architecture/workmanager/basics">Work Manager-Android Developers</a></p><p><a href="https://www.youtube.com/watch?v=IrKoBFLwTN0">Work Manager from the Android Developers Youtube Channel</a> from Google i/o 18.- This video link also describes how the Work Manager operates under the hood. A snapshot of the same is being give here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTkR7PSiwQ1vvPZCx9xftg.png" /></figure><p>That’s all about WorkManager! Hope this article has been of use to you and has given you a basic idea of how Work Manager is useful for us.</p><p>Thank you so much for your time.</p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cdb66c9a1df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/work-manager-in-android-9cdb66c9a1df">Working With WorkManager in Android Like A Pro</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[Dagger-Android-Part 5]]></title>
            <link>https://medium.com/mindorks/dagger-android-part-5-a67a724cea84?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67a724cea84</guid>
            <category><![CDATA[android-app-developers]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 09:23:15 GMT</pubDate>
            <atom:updated>2019-04-27T10:47:01.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvFBL_OmJvwDIN9hz86thQ.png" /></figure><p>Welcome to the fifth and the final part of this Dagger series. I hope you had enjoyed learning concepts and implementing things till <a href="https://link.medium.com/WWfiDr81dW">Part 4</a>.</p><p>In this part, we are going to introduce <strong><em>@Inject</em></strong> into our application.</p><p>Until now, we have created all our classes, modules and components for preparing our required dependencies. Now it’s time to inject those prepared dependencies in our application.</p><p>As discussed in the previous part, we will be continuing working on the following project:</p><p><a href="https://github.com/asdheeraj/SimpleDagger">asdheeraj/SimpleDagger</a></p><p>Firstly, let’s update our MyApplication class:</p><pre><strong>class </strong>MyApplication :Application() {<br><br>    <strong>lateinit var applicationComponent</strong>: ApplicationComponent<br><br>    @Inject<br>    @field:MarutiCar<br>    <strong>lateinit var marutiCar</strong>: Car<br><br>    <strong>override fun </strong>onCreate() {<br>        <strong>super</strong>.onCreate()<br><br>        <strong>applicationComponent </strong>= DaggerApplicationComponent<br>            .builder()<br>            .applicationModule(ApplicationModule(<strong>this</strong>))<br>            .build()<br>           <strong>applicationComponent</strong>.inject(<strong>this</strong>)<br><br>        Log.d(<strong>&quot;MyApplication&quot;</strong>,<strong>&quot;${marutiCar</strong>.hashCode()<strong>}: ${marutiCar</strong>.<strong>name}&quot;</strong>)<br><br>    }<br>}</pre><p><strong>Note: </strong>Remember to add this application name in the manifest file.</p><pre>.....<br>&lt;<strong>application<br>        android:allowBackup=&quot;true&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;<br>        android:name=&quot;.MyApplication&quot;<br>.....</strong></pre><p>We can observe that we are injecting the MarutiCar here. We can go back to our ApplicationComponent interface and we can observe that we are using MarutiCarModule in the list of modules defined here. Since, we have defined the provideCar() method in MarutiCarModule and its scope as Singleton, we can inject the same here.</p><pre>@Provides<br>@Singleton<br>@MarutiCar<br><strong>fun </strong>provideCar(car:Car) = car</pre><p>The above code is from MarutiCarModule class.</p><p>Also, we are defining an applicationComponent. The DaggerApplicationComponent class is the class that is generated by Dagger implementing the ApplicationComponent interface we discussed in our <a href="https://link.medium.com/WWfiDr81dW">Part 4</a> of the series. Once the project is built successfully, you can see the DaggerApplicationComponent class being generated and it looks like follows:</p><pre><strong>....<br>public final class </strong>DaggerApplicationComponent <strong>implements </strong>ApplicationComponent {<br>  <strong>private </strong>Provider&lt;String&gt; <strong>provideNameProvider</strong>;<br><br>  <strong>private </strong>Provider&lt;Car&gt; <strong>carProvider</strong>;<br><br>  <strong>private </strong>Provider&lt;Car&gt; <strong>provideCarProvider</strong>;<br><br>  <strong>private </strong>DaggerApplicationComponent(MarutiCarModule marutiCarModuleParam) {<br><br>    initialize(marutiCarModuleParam);<br>  }<br>...</pre><p>We have defined another component called ActivityComponent in <a href="https://link.medium.com/WWfiDr81dW">Part 4</a>. Let’s use that in our MainActivity class:</p><pre><strong>class </strong>MainActivity : AppCompatActivity() {<br><br>    <strong>lateinit var activityComponent</strong>: ActivityComponent<br><br>    @Inject<br>    @field:MarutiCar<br>    <strong>lateinit var marutiCar</strong>: Car<br><br>    @Inject<br>    @field:ToyotaCar<br>    <strong>lateinit var toyotaCar</strong>: Car<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_main</em>)<br><br>        <strong>activityComponent </strong>= DaggerActivityComponent<br>            .builder()<br>            .applicationComponent((<em>application </em><strong>as </strong>MyApplication).<strong>applicationComponent</strong>)<br>            .activityModule(ActivityModule(<strong>this</strong>))<br>            .build()<br><br>        <strong>activityComponent</strong>.inject(<strong>this</strong>)<br><br>        Log.d(<strong>&quot;MainActivity: &quot;</strong>, <strong>&quot;${marutiCar</strong>.hashCode()<strong>}: ${marutiCar</strong>.<strong>name}&quot;</strong>)<br>        Log.d(<strong>&quot;MainActivity: &quot;</strong>, <strong>&quot;${toyotaCar</strong>.hashCode()<strong>}: ${toyotaCar</strong>.<strong>name}&quot;</strong>)<br><br>        @SuppressLint(<strong>&quot;SetTextI18n&quot;</strong>)<br>        tv_displayName.<em>text </em>= <strong>&quot;${marutiCar</strong>.<strong>name}, ${toyotaCar</strong>.<strong>name}&quot;<br><br>    </strong>}<br>}</pre><p><strong>Exercise: </strong>What happens if we remove the @field from both toyotaCar and marutiCar. Give it a try!</p><p>We have included our ToyotaCarModule in our ActivityComponent, and, we are providing the car in the ToyotaCarModule class.</p><pre>@Provides<br>@ActivityScope<br>@ToyotaCar<br><strong>fun </strong>provideCar(car: Car) = car</pre><p>The above code is from ToyotaCarModule class.</p><p><strong>Exercise: </strong>What happens if we change the scope from ActivityScope to Singleton in the above code snippet? Just give it a try, change and compile it!</p><p>We have a layout file, activity_main.xml as follows:</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>androidx.constraintlayout.widget.ConstraintLayout<br>        xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        tools:context=&quot;.MainActivity&quot;</strong>&gt;<br><br>    &lt;<strong>TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;Hello World!&quot;<br>            android:id=&quot;@+id/tv_displayName&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>            app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;</strong>/&gt;<br><br>&lt;/<strong>androidx.constraintlayout.widget.ConstraintLayout</strong>&gt;</pre><p>The textview will display the names of the variables marutiCar and toyotaCar.</p><p>That’s it! You’ve done it. Compile it and run the application. See the names of the cars on your screen!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E5nv_XmuDzbrwhp0" /><figcaption>Photo by <a href="https://unsplash.com/@jasonhogan?utm_source=medium&amp;utm_medium=referral">Jason Hogan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now, let’s do the exercise parts, let’s play with the application. Try to explore on the results which will give us a much better knowledge of Dagger. Please share your observations in the comments below.</p><p><strong><em>Go through the Dagger classes that are generated for the Components defined. You will have a clear working knowledge of the methods that are declared in the Components and Dagger.</em></strong></p><p>For example, the inject method of the DaggerActivityComponent is defined as follows in the Dagger class generated for this Component:</p><pre>@Override<br><strong>public void </strong>inject(MainActivity activity) {<br>  injectMainActivity(activity);<br>}<br><br>@Override<br><strong>public </strong>Car getCar() {<br>  <strong>return provideCarProvider</strong>.get();<br>}<br><br><strong>private </strong>MainActivity injectMainActivity(MainActivity instance) {<br>  MainActivity_MembersInjector.<em>injectMarutiCar</em>(<br>      instance,<br>      Preconditions.<em>checkNotNull</em>(<br>          <strong>applicationComponent</strong>.getCar(),<br>          <strong>&quot;Cannot return null from a non-@Nullable component method&quot;</strong>));<br>  MainActivity_MembersInjector.<em>injectToyotaCar</em>(instance, <strong>provideCarProvider</strong>.get());<br>  <strong>return </strong>instance;<br>}</pre><p>That’s how the required dependencies are provided by injecting the required methods in the Components.</p><p>That’s it for part 5 of the Dagger series. We have reached the end.</p><p>I sincerely thank you for your time and appreciate you, reaching all the way here.</p><p>I hope, this Dagger series is of some use. All the best.</p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67a724cea84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/dagger-android-part-5-a67a724cea84">Dagger-Android-Part 5</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[Dagger-Android-Part 4]]></title>
            <link>https://medium.com/mindorks/dagger-android-part-4-a6a8e031f4cd?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a8e031f4cd</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-developers]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 09:22:49 GMT</pubDate>
            <atom:updated>2019-04-27T10:53:13.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BzJjj7Mg2QUlGoJnip35w.png" /></figure><p>I hope that the prerequisites to understand Dagger covered in parts <a href="https://link.medium.com/Dxcu0rW1dW">1</a>, <a href="https://link.medium.com/OvTWiMH1dW">2</a> and <a href="https://link.medium.com/JIY29Y21dW">3</a> are understood.</p><p>If you haven’t visited them, I request you to go through these parts before continuing with this part of the series.</p><p>In this part of the series, we are going to start with the actual implementation of Dagger with a project.</p><p>We will be referring to this project for understanding Dagger</p><p><a href="https://github.com/asdheeraj/SimpleDagger">asdheeraj/SimpleDagger</a></p><p>This has everything implemented wrt Dagger. So, let’s understand it step by step, the way we learned the concepts in <a href="https://link.medium.com/Dxcu0rW1dW">Part 1</a>, <a href="https://link.medium.com/OvTWiMH1dW">Part 2</a> and <a href="https://link.medium.com/JIY29Y21dW">Part 3</a>.</p><p>Firstly before we proceed, let’s add the dependencies to the application level build.gradle file</p><pre><em>// Dagger<br></em>implementation <strong>&quot;com.google.dagger:dagger:</strong>$dagger_version<strong>&quot;<br></strong>kapt <strong>&quot;com.google.dagger:dagger-compiler:</strong>$dagger_version<strong>&quot;</strong></pre><p>Define the dagger_version in the project level build.gradle file:</p><pre>ext {<br>    dagger_version = <strong>&#39;2.21&#39;<br></strong>}</pre><p>Here, we are using kapt because we require annotations to be used in Dagger. Since kapt stands for Kotlin Annotation Processing Tool, we have to add the plugin in the application level build.gradle file :</p><pre>apply <strong>plugin</strong>: <strong>&#39;kotlin-kapt&#39;</strong></pre><p>Now, we have added the dependencies.</p><p>So, let’ s recall what wehavelearntin <a href="https://link.medium.com/Dxcu0rW1dW">Part 1</a>, <a href="https://link.medium.com/OvTWiMH1dW">Part 2</a> and Part 3. Firstly, we understood the basics of DI, how annotation processing is done and what it means, Qualifier and Scope, and then the Module, Provides, Inject and Component annotations.</p><p>Let’s implement our project also in a similar way. Firstly, let’s define scope and Qualifiers in our project:</p><pre>@Scope<br>@Retention(AnnotationRetention.<strong>RUNTIME</strong>)<br><strong>annotation class </strong>ActivityScope</pre><p>And now, the Qualifiers:</p><pre>@Qualifier<br>@Retention(AnnotationRetention.<strong>BINARY</strong>)<br><strong>annotation class </strong>MarutiCar<br><br>@Qualifier<br>@Retention(AnnotationRetention.<strong>BINARY</strong>)<br><strong>annotation class </strong>ToyotaCar<br><br>@Qualifier<br>@Retention(AnnotationRetention.<strong>BINARY</strong>)<br><strong>annotation class </strong>CarName</pre><p>The Role of Scope and Qualifiers is explained in <a href="https://link.medium.com/OvTWiMH1dW">Part 2</a> of the series. But in brief, let’s see what these marutiCar and ToyotaCar Qualifiers do. Both cars are of type Car and since to differentiate their respective properties in the application , we have used Qualifiers.</p><p>Now, let’s define our Model class, which is Car.</p><pre><strong>class </strong>Car @Inject <strong>constructor</strong>(<br>    @CarName <strong>val name</strong>: String<br>) {<br>    <strong>fun </strong>displayName() {<br>        <em>//Displays the name of the car<br>    </em>}<br>}</pre><p>Now, we have a model class. Let’s define our Modules now. Remember, Module annotation is used on a class that contributes to the dependency/Dagger graph, meaning, it contains methods that provides the dependencies.</p><p>Firstly, let’s create ActivityModule:</p><pre>@Module<br><strong>class </strong>ActivityModule(<strong>var activity</strong>: AppCompatActivity) {<br>    @Provides<br>    <strong>fun </strong>provideActivity(): Activity = <strong>activity<br></strong>}</pre><p>Application Module :</p><pre>@Module<br><strong>class </strong>ApplicationModule(<strong>val application</strong>: MyApplication) {<br><br>    @Provides<br>    @Singleton<br>    <strong>fun </strong>provideApplication() : Application = <strong>application<br><br>    </strong>@Provides<br>    @Singleton<br>    <strong>fun </strong>provideContext() : Context = <strong>application<br><br></strong>}</pre><p>MarutiCarModule :</p><pre>@Module<br><strong>class </strong>MarutiCarModule {<br>    @Provides<br>    @CarName<br>    <strong>fun </strong>provideName(): String = <strong>&quot;Maruti Swift Dzire&quot;<br><br>    </strong>@Provides<br>    @Singleton<br>    @MarutiCar<br>    <strong>fun </strong>provideCar(car:Car) = car<br>}</pre><p>ToyotaCarModule:</p><pre>@Module<br><strong>class </strong>ToyotaCarModule {<br>    @Provides<br>    @CarName<br>    <strong>fun </strong>provideName() : String = <strong>&quot;Toyota Innova&quot;<br><br>    </strong>@Provides<br>    @ActivityScope<br>    @ToyotaCar<br>    <strong>fun </strong>provideCar(car: Car) = car<br>}</pre><p>Now let’s define our Components. So components are basically the interfaces that connects the Dependency Providers (Module classes) and Dependency consumers.</p><p>Let’s define ApplicationComponent first:</p><pre>@Singleton<br>@Component(<br>    modules = [<br>        ApplicationModule::<strong>class</strong>,<br>        MarutiCarModule::<strong>class<br>    </strong>]<br>)<br><strong>interface </strong>ApplicationComponent {<br><br>    <strong>fun </strong>inject (application: MyApplication)<br><br>    @MarutiCar<br>    <strong>fun </strong>getCar() : Car<br>}</pre><p>We should define the module classes that are used in this ApplicationComponent. We are providing the scope for Application Component as @Singleton because we need the values throughout the application</p><p>Now, let’s define ActivityComponent:</p><pre>@ActivityScope<br>@Component(<br>    dependencies = [ApplicationComponent::<strong>class</strong>],<br>    modules = [ActivityModule::<strong>class</strong>,<br>            ToyotaCarModule::<strong>class</strong>]<br>)<br><strong>interface </strong>ActivityComponent {<br><br>    <strong>fun </strong>inject(activity: MainActivity)<br><br>    @ToyotaCar<br>    <strong>fun </strong>getCar() : Car<br>}</pre><p>Here, in activity component we are using dependencies = [ApplicationComponent::<strong>class</strong>], because, though this is a simple example, we might be providing singleton instances in the Application Module class which might be required in Activity Modules (like networkProvider etc.,). When these values are required by Activity Modules, they take them from the available Dagger/Dependency graph instead of creating new ones.</p><p>So, we have defined our Qualifiers, Scopes, Modules, Provides methods and Components. So we have everything ready at compile time. Now, let’s use them by using the <strong><em>@Inject </em></strong>in our final part, <a href="https://link.medium.com/8xUIU0b2dW">Part 5</a></p><p>Congratulations on applying the knowledge we have learnt from Part <a href="https://link.medium.com/Dxcu0rW1dW">1</a>, <a href="https://link.medium.com/OvTWiMH1dW">2</a> and <a href="https://link.medium.com/JIY29Y21dW">3</a> in this part.</p><p>That’s it for Part 4 of this series.</p><p>Thank you for your time!</p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a8e031f4cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/dagger-android-part-4-a6a8e031f4cd">Dagger-Android-Part 4</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[Dagger-Android-Part 3]]></title>
            <link>https://medium.com/mindorks/dagger-android-part-3-9f1936b99b60?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f1936b99b60</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 09:22:40 GMT</pubDate>
            <atom:updated>2019-04-27T10:26:50.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy_h2a8g8bn0pWeHMV4Pig.png" /></figure><p>Welcome to the Part 3 of this Dagger series. In the previous parts, we have learnt about Dependency Injection basics, annotation processing, usage of @Qualifier and @Scope in Dagger.</p><p>If you haven’t already gone through <a href="https://link.medium.com/Dxcu0rW1dW">Part 1</a> as and <a href="https://link.medium.com/OvTWiMH1dW">Part 2</a>, I would request you to go through them for better understanding of Dagger in the upcoming parts.</p><p>In this part of the series, we are going to look at the main annotations that are provided by the <em>javax.inject</em> package for Dagger. There are mainly four annotations that we are going to see in this part of the series. They are</p><ul><li>@Module</li><li>@Provides</li><li>@Inject</li><li>@Component</li></ul><p>Let’s discuss these <a href="https://blog.mindorks.com/improve-your-android-coding-through-annotations-26b3273c137a">annotations</a> one by one.</p><p>As discussed in the previous part, when a particular annotation is being used, let us understand its usage by looking at its respective source code.</p><h3>Module</h3><p>If we have a look at the source code of Module annotation, it contains the main statement as follows :</p><pre><em>....<br>/**<br> * Annotates a class that contributes to the object graph.<br> */<br></em>@Retention(RetentionPolicy.<strong><em>RUNTIME</em></strong>)<br>@Target(ElementType.<strong><em>TYPE</em></strong>)<br><strong>public </strong>@<strong>interface </strong>Module {<br>  <em>/**<br>...</em></pre><p>So, this annotation is used on a class that contributes to the object graph, here it is the Dagger graph or the dependency graph.</p><p><strong>What is object/Dagger/Dependency graph here?</strong></p><p>The Dependency graph is the graph that is created by Dagger which contains all the instances of the application that need to be injected at the required time. This graph is generated at compile time.</p><p>Now, let’s come back to our @Module annotation. This is used on any class that contributes to the Dependency graph. That means, it is used on any class that “provides” the dependency instance that can be used by Dagger to “inject” wherever necessary.</p><p>How is a dependency instance ‘provided’ or ‘injected’ ? Well, don’t worry. We’ve seen only one annotation so far. You will understand this when we complete this part of the series.</p><p>For now, just understand that @Module is used on any class that helps in providing the Dependency instance.</p><h3>Provides</h3><p>Let’s have a look at the source code of this annotation first.</p><pre><em>....<br>/**<br> * Annotates methods of a {</em><strong><em>@linkplain </em></strong><em>Module module} to create a provider method binding. The<br>....<br></em>@Documented @Target(<strong><em>METHOD</em></strong>) @Retention(<strong><em>RUNTIME</em></strong>)<br><strong>public </strong>@<strong>interface </strong>Provides {<br>}</pre><p>So, from the source code it is evident that this @Provides annotates methods of the <strong>Module </strong>class to create a provider method for binding. So let’s say Class A needs the instance of Class B. So here, there shall be a configuration class, let’s say Class C.</p><p>Class C will contain a method that returns Class B. Hence, the method that is returning Class B should be annotated with <strong><em>@Provides</em></strong> annotation.</p><p>Since this class is providing an instance of class B, it is contributing to the Dependency graph and hence should be annotated with <strong><em>@Module</em></strong></p><pre>@Module<strong><br>class classC {</strong></pre><pre>@Provides<br>fun classBProvider(): classB {<br>    <strong>return </strong>classB()<strong><br></strong>}</pre><pre><strong>}</strong></pre><h3>Inject</h3><p>Let’s have a look at the source code of Inject annotation</p><pre><em>.....<br>/**<br> * Identifies injectable constructors, methods, and fields.<br>....<br></em>@Target({ <strong><em>METHOD</em></strong>, <strong><em>CONSTRUCTOR</em></strong>, <strong><em>FIELD </em></strong>})<br>@Retention(<strong><em>RUNTIME</em></strong>)<br>@Documented<br><strong>public </strong>@<strong>interface </strong>Inject {}</pre><p><strong>Note: </strong>The source codes mentioned here just represents the basic definition of annotations. To know more about the same, it is highly recommended to go through the entire source code.</p><p>So, from the definition, this annotation is used when the necessary instance that needs to be used in a respective class is not defined (to avoid tight coupling) and needs to be injected.</p><p>In our above example, since Class B instance needs to be used in Class A. There should be a field in Class A with <strong><em>@Inject </em></strong>annotation as follows:</p><pre>@Inject<strong><br>lateinit var </strong>instanceB<strong>: ClassB</strong></pre><p>So, when the Inject annotation is seen, Dagger looks for its corresponding <strong><em>@Provides </em></strong>method that returns a classB instance. Here, the method is classBProvider() in classC.</p><h3>Component</h3><p>Firstly, let’s have a look at the Component source code.</p><pre><em>...<br>/**<br> * Annotates an interface or abstract class for which a fully-formed, dependency-injected implementation is to be generated from a set of {</em><strong><em>@linkplain </em></strong><em>#modules}. <br>....<br></em>@Retention(<strong><em>RUNTIME</em></strong>) <em>// Allows runtimes to have specialized behavior interoperating with Dagger.<br></em>@Target(<strong><em>TYPE</em></strong>)<br>@Documented<br><strong>public </strong>@<strong>interface </strong>Component {<br>....</pre><p>So, this needs to be used on an interface/abstract class. The Scope that we discussed in our previous part, will be defined in this Component. So that the respective Activity,Fragment or Application using this respective component will get their set of Dependencies that are required by them in the respective scope that is defined in the Component.</p><p>This Component also provides the methods that need to be exposed so that the Dagger class generated for this Component can provide us with the respective dependencies</p><p>When a scope is declared in a Component, it may only contain un-scoped Bindings or bindings with that scope anywhere in the graph.</p><p>We will get to know the implementation of <strong><em>@Component </em></strong>in our example which we will be implementing in <a href="https://link.medium.com/WWfiDr81dW">Part 4</a> and <a href="https://link.medium.com/8xUIU0b2dW">Part 5</a> of the series.</p><p>For now, understand that this interface/abstract class defines the connection between the provider of objects (modules) and the objects which express a dependency. The class for this connection is generated by the Dagger.</p><p>That’s it for this part of the series.</p><p>Please refer the <a href="https://link.medium.com/WWfiDr81dW">Part 4</a> of the series <a href="https://link.medium.com/WWfiDr81dW">here</a></p><p>Congratulations for getting introduced to the important <a href="https://blog.mindorks.com/improve-your-android-coding-through-annotations-26b3273c137a">annotations</a> that are used in Dagger.</p><p>Thank you for your time.</p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><p>References:</p><ul><li><a href="https://blog.mindorks.com/a-complete-guide-to-learn-dagger-2-b4c7a570d99c">A Complete Guide To Learn Dagger 2</a></li><li><a href="https://blog.mindorks.com/introduction-to-dagger-2-using-dependency-injection-in-android-part-1-223289c2a01b">Introduction to Dagger 2, Using Dependency Injection in Android: Part 1</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f1936b99b60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/dagger-android-part-3-9f1936b99b60">Dagger-Android-Part 3</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[Dagger-Android-Part 2]]></title>
            <link>https://medium.com/mindorks/dagger-android-part-2-9be9f2d169ca?source=rss-e9fc16195c5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be9f2d169ca</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[dagger]]></category>
            <dc:creator><![CDATA[Dheeraj Andra]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 09:22:11 GMT</pubDate>
            <atom:updated>2019-04-27T10:14:38.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkDJaL0Upg2L0yRWpJIlMA.png" /></figure><p>Welcome to the part 2 of this Dagger Series. In the previous part we have understood what Dependency Injection in Software Development is and what Dagger is used for.</p><p>If you haven’t already gone through the first part of the series, I would request you to give a look <a href="https://medium.com/p/31ede7ad1998/edit">here</a> for better understanding of Dependency Injection.</p><p>In this part of the series, we are going to discuss what is Annotation processing and different kinds of annotation we use in Dagger like Scope and Qualifier.</p><p>More often, when we use Dagger in our Android Application Development, we see some classes containing <strong>@Module, @Inject, @Provides, @Scope, @Qualifier , etc., </strong>What is the common thing that we observe among all these terms? The Symbol “@”. These are called annotations and help us very much in avoiding repetitive code.</p><p>So, let’s understand what annotations are and how does annotation processing help us in better coding by observing the <strong>@Override </strong>annotation.</p><p>We have come across this <strong>@Override </strong>annotation many a time whenever we extend an abstract class or an interface. Implementing the abstract methods in our custom class implies that we are overriding the respective method that is defined in the parent class.</p><p>Let’s take a quick and simple example. Let’s create a base class Car. And let this base class be extended by a custom class. Let’s call the custom class BMW. BMW uses the common functionalities that are present in the parent Car class, but some of the properties may differ. Let’s say there is a method calculateTopSpeed() in the parent Car class. The definition of this method will not be the same for BMW and hence it overrides that method and gives its own definition.</p><p>In the source code for @override , it is mentioned that the method on which this annotation is used overrides or implements a method that is declared in the super type.</p><pre><strong>package </strong>java.lang;<br><br><strong>import </strong>java.lang.annotation.*;<br><em><br></em>@Target(ElementType.<strong><em>METHOD</em></strong>)<br>@Retention(RetentionPolicy.<strong><em>SOURCE</em></strong>)<br><strong>public </strong>@<strong>interface </strong>Override {<br>}</pre><p>To learn more on annotations, please refer to this blog:</p><p><a href="https://blog.mindorks.com/improve-your-android-coding-through-annotations-26b3273c137a">Improve Your Android Coding Through Annotations</a></p><p>Whenever we use annotations, try understanding the basic definition of the respective annotation by referring the source code. We will be understanding the main annotations(Module, Component, Inject and Provides) that are being used in Dagger in a much better way in our next part of the series. For now I hope you have understood the basic definition of annotations being used in Android Development.</p><p>Let’s understand the annotations @Qualifier and @Scope in this part of the series.</p><p>Qualifiers help in differentiation of the objects(of the same type) that are being injected. Fore more information and better understanding of Qualifiers, please refer to this blog :</p><p><a href="https://medium.com/mindorks/qualifiers-in-dagger-android-development-c0574cca87a2">Qualifiers in Dagger-Android Development</a></p><p>Now, let’s understand @Scope annotation. We will be using this in our code that we are going to develop in Part 4 and Part 5 of the series. But for now, lets understand @Scope with a simple example provided in the following blog:</p><p><a href="https://medium.com/tompee/dagger-2-scopes-and-subcomponents-d54d58511781">Dagger 2: Scopes and Subcomponents</a></p><p>Let’s consider the code snippet provided in the mentioned blog:</p><p>Firstly, let’s define our own scope(Application Scope). We create a custom scope by using @Scope annotation.</p><pre>@Scope<br>@Retention<br>annotation class ApplicationScope</pre><p>Now, let’s create an unscoped component to understand the power of @Scope</p><pre>data class Warrior(val name: String)<br><br>@Component(modules = [AppModule::class])<br>interface AppComponent {<br>    fun getWarrior(): Warrior<br>}<br><br>@Module<br>class AppModule {<br>    private var index = 0<br><br>    @Provides<br>    fun provideWarrior(): Warrior {<br>        index++<br>        return Warrior(&quot;Warrior $index&quot;)<br>    }<br>}</pre><p>We can see that there is no scope that is provided here. Now, let’s define a data class Warrior with a name property. This will serve as our dependency. Next we define a module that provides this dependency. But every time a new warrior is instantiated, we increment the index. This will help us to figure out if indeed a new instance is created every time. Finally a component that exposes this dependency. Then let us instantiate in our application.</p><p>Don’t be confused with the Dagger annotations that are being used in the code snippet. We will be covering them in our next part of the series.</p><pre>class WarriorApplication : Application() {<br>    private val TAG = &quot;WarriorApplication&quot;<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        val appComponent = DaggerAppComponent.builder()<br>                .appModule(AppModule())<br>                .build()<br>        Log.d(TAG, appComponent.getWarrior().name)<br>        Log.d(TAG, appComponent.getWarrior().name)<br>    }<br>}</pre><p>Running the app will output these logs:</p><pre>D/WarriorApplication: Warrior 1<br>D/WarriorApplication: Warrior 2</pre><p>We can see that two different instances are created. This is expected as the component and dependency is unscoped. Now let us annotate our component and provide method with our new scope.</p><pre>@ApplicationScope<br>@Component(modules = [AppModule::class])<br>interface AppComponent {<br>    fun getWarrior(): Warrior<br>}<br><br>@Module<br>class AppModule {<br>    private var index = 0<br><br>    @ApplicationScope<br>    @Provides<br>    fun provideWarrior(): Warrior {<br>        index++<br>        return Warrior(&quot;Warrior $index&quot;)<br>    }<br>}</pre><p>Running the application will now output the following logs</p><pre>D/WarriorApplication: Warrior 1<br>D/WarriorApplication: Warrior 1</pre><p>Notice that the same instance is returned to us. This is the power of scoping. It provides us local singletons within the defined scope. Now, the scope is only valid within the component. When a new component of the same type is initialised, it will have a new sets of dependencies. This is the reason why @Singleton components are instantiated and maintained in the Application class. The singleton application component should persist throughout the application lifecycle, and the app should refer to this component to uphold that “single instance” requirement.</p><p>Congratulations on understanding the basic introduction to annotation processing, @Qualifier and @Scope.</p><p>We will be understanding the rest of the annotations used in Dagger in our next part of the series.</p><p>That’s it for part 2 of this series. Thank you for your time.</p><p>You can refer the <a href="https://link.medium.com/JIY29Y21dW">Part 3</a> of the series <a href="https://link.medium.com/JIY29Y21dW">here</a></p><p>Let’s connect on <a href="https://twitter.com/AndraDheeraj">Twitter</a> and <a href="https://www.linkedin.com/in/dheerajsree/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be9f2d169ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/dagger-android-part-2-9be9f2d169ca">Dagger-Android-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>
    </channel>
</rss>