<?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 Balarka Velidi on Medium]]></title>
        <description><![CDATA[Stories by Balarka Velidi on Medium]]></description>
        <link>https://medium.com/@balarkav?source=rss-f164f3664db0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GimU3Jz2d5KJcqU317nvww@2x.jpeg</url>
            <title>Stories by Balarka Velidi on Medium</title>
            <link>https://medium.com/@balarkav?source=rss-f164f3664db0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:08:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balarkav/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[How to Reduce Android Mobile App Data Sync Start-up Times to Delight Your Customers]]></title>
            <link>https://medium.com/intuit-engineering/how-to-reduce-android-mobile-app-data-sync-start-up-times-to-delight-your-customers-e358e549e0b9?source=rss-f164f3664db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e358e549e0b9</guid>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[data-model]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Balarka Velidi]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 20:00:28 GMT</pubDate>
            <atom:updated>2022-04-05T20:08:57.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ClqaV90q3FNnxI_y5soCsQ.jpeg" /></figure><p>At Intuit, we’re proud to solve hard problems and constantly strive to deliver unrivaled benefits to our consumer, small business and self-employed customers on our mission to power prosperity around the world.</p><p>In this blog post, we’ll explain our approach to optimizing Intuit’s <a href="https://play.google.com/store/apps/details?id=com.intuit.quickbooks">QuickBooks Android</a> mobile app during the onboarding stage, the challenges we faced, and lessons learned along the way. We’ll take a deep dive into our journey to finding a reliable solution that not only improves the overall efficiency of the onboarding experience, but improves customer delight.</p><p>We’re all familiar with mobile apps which take time to load data upon launch, making us feel frozen in time. Historically, mobile apps are architected to download/fetch as much data as possible from back-end APIs to provide an offline experience to the user. This is especially true for mobile apps that are database-centric, with a sole goal is to load up with data that might be used later.</p><p>Intuit’s <a href="https://quickbooks.intuit.com/accounting/mobile/">QuickBooks Mobile app</a> helps customers create and manage invoices, estimates, vendors, expenses, sales receipts, etc., all stored in a local database during app onboarding. When fetched from back-end APIs, all of this data may take significant time over 3G, LTE, even Wi-Fi networks, in extreme cases.</p><p>Apps typically show a spinner screen while fetching all the required data behind the scenes. If shown for considerably longer periods, this “infinite spinner” screen can lead to a bad onboarding experience for users, resulting in bad/low-star reviews in app stores.</p><p><strong>Before we begin..<br></strong>With the <a href="https://play.google.com/store/apps/details?id=com.intuit.quickbooks&amp;hl=en_US&amp;gl=US">QuickBooks Android Mobile App</a>, 225K Intuit customers track their finances, create invoices, log miles, and track their profit and loss reports each month, in addition to solving for many other accounting needs. The mobile app is architected to be database-centric and relies heavily on a relational database management framework/system provided by <a href="https://developer.android.com/training/data-storage/room">Android’s Room/SQLite framework</a> to power most of the app’s critical data needs. The app builds entity data models (to support various accounting workflows like invoices, estimates, or vendors) by fetching domain models from corresponding back-end services.</p><p><strong>The Data Sync Process<br></strong>The app fetches about 25 entity data models and writes them to local database persistence storage. This process (internally known at Intuit as data sync) happens during customer onboarding at app launch and is a mandatory step for completion, after which the customer is taken to the dashboard/home screen. The app also triggers this process at a regular interval in the background to keep the app’s data in sync with server-side changes.</p><p>During onboarding, the app displays a “Loading company data..” screen (see Diagram 1 below) while the data sync process completes, so the customer must wait before continuing to use the app.</p><figure><img alt="Data Loading screen of QuickBooks Mobile App" src="https://cdn-images-1.medium.com/max/303/1*FxWxICuDQU5Wbgu4lM4v3Q.png" /><figcaption>Diagram 1: App’s “Data Loading” blocker screen</figcaption></figure><p>This data sync start-up process takes about 12 seconds to complete, according to our internal real user monitoring (RUM) metrics and collectively runs about 10,000 times per day, across all Android QuickBooks Mobile user devices combined (for TP90 metric, see Chart 1 below.)</p><figure><img alt="Real-User Monitoring (RUM) metrics of data sync process duration" src="https://cdn-images-1.medium.com/max/640/1*8kss9X6HeDeNZgGWMZoLZQ.png" /><figcaption>Chart 1. Data sync process duration (TP90 metric in milliseconds)</figcaption></figure><p><strong>So, what’s the problem?<br></strong>Customers with a wide variety of company data sizes use the app daily. This mandatory data sync start-up process needs to run and complete quickly. But for customers with huge company data sizes, this can take far too long. At least that’s where our team decided to focus at the beginning. Suffice to say we had some aha moments along the way!</p><p><strong>How did we solve it?<br></strong>Let’s go over the approaches on the client side (Android app) and the roadblocks we hit.</p><p><strong>#1 Deep dive into individual entity APIs:<br></strong>To find the root cause of this problem, we dug deep to identify specific entities that took way too long to fetch from back-end services by collaborating with back-end teams here at Intuit.</p><p>This posed our first challenge: most of these entities came from one single back-end batch API and there wasn’t a predictable way to identify which entity endpoints in the backend were slow. Breaking this single batch REST (representational state transfer) API into individual APIs was doable, but came with other complex changes in the app’s data layer (a task for another day), so this approach didn’t prove viable, either.</p><p><strong>#2 Fetch important entities first:<br></strong>We then moved on to group the entities based on varying degrees of importance, fetching only the group(s) with the highest importance and deferring the rest to later stages. With this approach, we hit another challenge. Given how the app is used by customers with different business needs (small businesses, accountant firms) in our small business ecosystem, it was close to impossible to predict non-critical entities whose fetching could be avoided. So, unfortunately this approach didn’t see the light.</p><p><strong>#3 Try adding pagination limits:<br></strong>We looked into the entity data itself to see if we could ask for fewer entities from each of the batch APIs and introduced pagination for as many entity fetches as possible. As we looked at each entity’s request payload, we noticed that the ‘epoch’ field would ask the server to return only the changed records, while some entity batch requests had a pagination field to fetch the last 1000 records ever created. A few entities, however, didn’t have fields in the request payload. Upon further investigation, back-end APIs didn’t support either ‘epoch’ or ‘pagination’. So, we hit another dead end. Still, we persisted!</p><p><strong>#4 Try bypassing the blocking data sync screen:<br></strong>At this point, we concluded that the data sync process was unavoidable.</p><p>We wanted to see whether it might be possible to bypass the loading blocker screen display in the forefront — in certain scenarios when the data sync process could proceed unobtrusively behind the scenes. This was our aha moment.</p><p>With our overall QuickBooks mobile customer experience in mind, we pivoted to a different approach. We set out to dramatically reduce the total number of times data sync would run in the forefront across all Android devices each month, collectively, to improve customer experiences across a variety of small business data sizes and use cases, rather than explicitly reducing average data sync time per instance. In other words, we looked to solve the problem at a system-level rather than a per-instance occurrence level.</p><p>To answer the question of whether we could bypass the loading blocker screen display, we looked under the hood of the app’s data sync process and related database logic. After signing into QuickBooks Mobile app, the user would select a company file to work on. The data sync process began to fetch all related entity data about that company and to insert them into the database, and it was very common for a single customer to have multiple companies to choose from.</p><p>As we went deeper into the app code, we noticed there was a one-to-one mapping between the selected company and the database file created. This meant that whenever a user selected a new company, the app created a brand new database file on the device.</p><p>To efficiently let customers switch between companies, the app always kept previously created database file(s) intact and never deleted them (though the user could manually wipe out the app’s disk storage from operating system settings). With the help of <a href="https://developer.android.com/training/data-storage/sqlite">Android’s SQLite Framework</a>, we could reliably see when a database was created for the first time. Based on this first time creation, a flag (boolean) could be stored along with the corresponding company ID into a Java HashMap, and referred to later for the app to decide whether a data sync would be required.</p><p>Armed with these insights, we constructed a set of criteria to help us identify whether, for a given company, there was a need to begin the data sync process (and display the “Data Loading…” blocking screen) before letting the user go to the dashboard screen.</p><p>However, a new problem popped up with the above design. The in-memory Java HashMap object got wiped out whenever the app was shut down by the user or operating system (for example, due to low memory constraint) and wasn’t itself a reliable solution.</p><p>So, we augmented our criteria to check whether the database file existed on the device and, if so, we could determine that the entity data was already present (since the app never deletes tabular data from the database).</p><p>With this change, the criteria to trigger data sync was established in this order:</p><ol><li>Check if in-memory HashMap contains entry with flag set to ‘true’</li><li>Check if the database file on the device is already created (final source of truth)</li></ol><p>With the above criteria in place, we knew when to perform the blocking data sync operation.</p><p>But, we still needed to perform non-blocking data sync operations to fetch the latest data from back-end services, otherwise the app data would be stale. To achieve this, we triggered the data sync process behind the scenes and displayed a “data sync running” toast message, while simultaneously enabling customers to continue using the app (see Diagram 2 below).</p><figure><img alt="QuickBooks Mobile Dashboard screen with bottom Toast message" src="https://cdn-images-1.medium.com/max/303/1*N_X5N5TDfKMJsP0IN2orvA.png" /><figcaption>Diagram 2: Data Sync process running behind the scenes</figcaption></figure><p><strong>Results<br></strong>As seen in ‌Diagram 3 below, we previously had about 121,000 instances of data sync each month, reflecting the total number of times data sync ran across all Android devices out there.</p><figure><img alt="Data Sync Process Instances before changes" src="https://cdn-images-1.medium.com/max/640/1*mktonnNMZE3ot0HN42IJXA.png" /><figcaption>Diagram 3: Before Optimization Total Data Sync Instances in a Month</figcaption></figure><p>After applying this new approach to data sync optimization, total data sync instances dropped to 36,000 during the same period (see Diagram 4). That was a 70 percent reduction in total data sync occurrences for situations in which users already had a database (with the data) and could use the app immediately, without delay!</p><figure><img alt="Data Sync Process Instances after changes" src="https://cdn-images-1.medium.com/max/640/1*s4o4SJN7m2NPFWMA_8DQ5w.png" /><figcaption>Diagram 4: After Optimization Total Data Sync Instances in a Month</figcaption></figure><p><strong>What did it mean?<br></strong>Previously, there were about 10K data sync occurrences per day, each taking ~12s (TP90) to complete (120K seconds). With the above optimization, we observed a 70 percent reduction in total number of data syncs, which came down to 84k seconds (120K * 0.70) or 23.3 hours.</p><p>In other words, we saved a whopping ~23 hours per day for our customers, who otherwise would have to wait to use the app until it completed loading data!</p><p><strong>So, any takeaways?<br></strong>Below are a few learnings gleaned from this optimization that might be helpful to others looking to optimize data sync time for Android app onboarding.</p><ul><li><strong>Change perspective as needed. </strong>If the selected approach didn’t help to solve the problem, we had to zoom out. Our initial approaches were all making sense when looking at improving the data sync process efficiency, while displaying the loading screen. However, looking at a higher altitude helped us answer an important question: Was the loading screen needed in the first place? Changing perspective helped us to pivot after plowing through various approaches that got tough along the way. And, it exemplifies a guiding principle we abide by here at Intuit: “fall in love with the customer problem, not the solution.”</li><li><strong>Pros and cons for every approach.</strong> We realized there will be pros and cons for every approach, so it was important to always keep the use case in mind. Specifically, having a single batch API to fetch all entities had certain advantages (e.g., single API call to back-end services per mobile client, single I/O thread). However, having a single API call also obfuscated critical details (e.g., the time taken by individual entity fetches), making it hard to identify and improve slow-running back-end entity APIs.</li><li><strong>Leave no stone unturned. </strong>While it made total sense to go deep into the software components we knew and were comfortable with, a simpler solution could be found in other cross-stack software systems. For example, we went over all entity fetch API request payloads to see if we could introduce pagination size limits, and noticed all entity requests were up to date, as supported by the corresponding back-end APIs. This investigation paved the way for other important conversations with back-end Intuit teams to improve the APIs, making them mobile friendly.</li></ul><p><strong>Wrap Up<br></strong>Solving challenging problems can take considerable effort. Brainstorming and experimenting with a seemingly endless number of approaches can be discouraging — especially when many of them don’t prove viable. Using Android SQLite framework’s APIs directly, we are able to reliably identify and distinguish between database storage-creation nuances without any convoluted business logic. And, now the app’s database layer is clean, maintainable, and easy to understand and work with, leading to a significantly better customer experience.</p><p><strong>Before you go<br></strong>Thanks for reading! We hope this post provides useful insights and thoughtful ideas for solving mobile app challenges. If you are passionate about solving interesting problems and challenges, chat with us and join the team! The QuickBooks Mobile team is actively hiring.</p><p>Below are job openings in our team — join our <a href="https://www.intuit.com/careers/talent-community/">talent community</a> to learn more!</p><p>Software Engineer 2: <a href="https://jobs.intuit.com/job/mountain-view/software-engineer-2-android/27595/20948744432">https://jobs.intuit.com/job/mountain-view/software-engineer-2-android/27595/20948744432</a></p><p>Senior Software Engineer: <a href="https://jobs.intuit.com/job/mountain-view/senior-software-engineer-android/27595/20948744336">https://jobs.intuit.com/job/mountain-view/senior-software-engineer-android/27595/20948744336</a></p><p>Staff Software Engineer: <a href="https://jobs.intuit.com/job/mountain-view/staff-software-engineer-android/27595/20948744128">https://jobs.intuit.com/job/mountain-view/staff-software-engineer-android/27595/20948744128</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e358e549e0b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intuit-engineering/how-to-reduce-android-mobile-app-data-sync-start-up-times-to-delight-your-customers-e358e549e0b9">How to Reduce Android Mobile App Data Sync Start-up Times to Delight Your Customers</a> was originally published in <a href="https://medium.com/intuit-engineering">Intuit Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building SwipeView using MotionLayout]]></title>
            <link>https://proandroiddev.com/building-swipeview-using-motionlayout-7a80fd06401c?source=rss-f164f3664db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a80fd06401c</guid>
            <category><![CDATA[swipe-view-android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <dc:creator><![CDATA[Balarka Velidi]]></dc:creator>
            <pubDate>Sun, 08 Nov 2020 23:01:23 GMT</pubDate>
            <atom:updated>2020-11-17T00:50:47.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quJ3zQVPBolUA_aRwjrrfg.jpeg" /></figure><p>MotionLayout (a subclass of ConstraintLayout) is aimed at making user controlled animations very easy and maintainable. It was first introduced in Google I/O ’18 and since then it has been going through many improvements. An awesome editor (a.k.a MotionEditor) support was added in Android Studio. I have been playing with its powerful API to build components with animations to common user events.</p><p>Most popular messaging, email apps feature a swipe behavior on individual message/email items to provide more contextual actions relevant to that item. For example, this is how Gmail app email swipe looks like; swipe left to archive message, and swipe right to delete message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*SEKOJoT2hSDF91FwvfOTrA.gif" /><figcaption>Email Swipe behavior in Gmail app</figcaption></figure><p>In this article, I explain implementing a SlideView component (ex: sliding an email in popular email apps like Gmail, outlook, yahoo etc.. or messages in Messages app) using MotionLayout instead of other traditional ways. To illustrate the MotionLayout and its animation features, I used a simple view element (like TextView) on which swipe actions can be performed. But this view can be easily replaced by a complex Custom View with the same rest of the behaviors/animations. Once finished, the example looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ABIRC2xndiuQbYTjunXPQ.gif" /><figcaption>Swipe View built using MotionLayout</figcaption></figure><p>Let’s begin. First, we need to get the MotionLayout and its relevant library classes in our dependencies. MotionLayout is being released inside Constraintlayout.2.0</p><p>Add this to app/build.gradle and do grade sync, we are good to go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/616282dc634e444ea6382cf510682bc7/href">https://medium.com/media/616282dc634e444ea6382cf510682bc7/href</a></iframe><p>MotionLayout (similar to ConstraintLayout) lays out its children elements using their constraints (w.r.t parent or sibling views). However, since MotionLayout specifically enables us to animate views more seamlessly via its powerful API, it requires us to split the UI representation and User events/view animations in two different files. Let’s go into more details.</p><ol><li>It needs a layout file that specifies all the views in the view hierarchy. Let’s call it <em>motion_layout.xml</em></li><li>It needs a separate file to explain the motion scene, where we describe the start and end states of transitions with the user behavior attached (if any). Let’s call it <em>motion_scene.xml</em></li></ol><p>Both of these files are linked together via the layoutDescription tag in the MotionLayout node.</p><p><strong>Building the MotionLayoutSwipeView:</strong></p><p>In our case, we want to build a view that has the ability to slide left and right based on user’s swipe action while revealing or hiding certain other views as needed. For example, in a typical email app, when user swipes the view towards left, we would like to show a “Forward” and “Archive” actions. When the user swipes to the right, we would like to show a “delete” action with some animation attached to it providing visual cues that the email is deleted.</p><p>Step 1:</p><p>The first step is to build the MotionLayout’s layout file, with all the relevant UI views appearing in the rest/start state. For the sake of simplicity, I’d like to use a TextView as the view to be swiped, but this can be easily replaced with any Custom View.</p><p>So the motionLayout root has all the children views, a TextView to show some text that the user can swipe on. A Delete ImageView for delete action, Forward and archive ImageViews for forward/archive actions respectively.</p><p>Now the <em>motion_layout.xml</em> will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c60158fe275a5f6d99800b1a0db4987/href">https://medium.com/media/7c60158fe275a5f6d99800b1a0db4987/href</a></iframe><p>Step 2:</p><p>The next step is to define the content of <em>motion_scene.xml</em> (with a MotionScene root node). Here we need to specify all the various states that our views go through and their corresponding transitions and animations. A State contains all the information pertaining to how the views are aligned in that particular state. State details are specified via ConstraintSet tag/class. The Transition tag describes the MotionLayout system a journey between two states, the duration for that journey and other user actions (if any).</p><p>In our use case, we have one swipe left action that changes the UI from two states i.e from rest/start state to a state where forward/archive image views are shown, let’s call this end state as “end1”. We also have another swipe right action, that changes the UI from rest/start state to a state where we show delete image view, let’s call this end state as “end2”. So we have a total of 3 states, and 2 user behaviors (a.k.a transitions). Let’s name the transitions leftSwipe and rightSwipe.</p><p>Our 3 states (start, end1, end2) are specified along with the view alignment as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fae8141fd44f9d4a4e729c53abc6aca/href">https://medium.com/media/9fae8141fd44f9d4a4e729c53abc6aca/href</a></iframe><p>The transition details are specified via the <strong>Transition</strong> tag with a name for the transitions, start and end states. The example below shows the transition from “start” to “end” states in <em>motion_scene.xml</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f5bbec649768500f37264fe97451abe/href">https://medium.com/media/2f5bbec649768500f37264fe97451abe/href</a></iframe><p>With this, we should have basic user interaction of the swipe views and corresponding views being shown accordingly as needed. As you might have noticed, we have not touched anything inside the Activity for any of this behavior! This is where MotionLayout shines bright (compared to various other Layouts) and where complex motion animations can be achieved without writing a single line of code! The layout, its states, animations and transitions are self-contained in XML files.</p><p>We are not finished yet.</p><p>For a typical delete action, the message/email should be removed from the UI screen, and behind the scenes a database/network call needs to be made to update the record accordingly. Focusing on the UI aspect of this, to build a delightful visual experience, we need to show the user some animation when the delete action is selected. For example, we can fade out the delete icon at the end of the swipe right user action for example. MotionLayout makes it very easy to achieve this, and we shall see how.</p><p>MotionLayout provides an API to listen to various transitions it plays on its children view, and we can add our own custom transition listener via addTransitionListener method of MotionLayout class. This is done inside <strong>Activity</strong> class that is inflating the motion_layout.xml</p><p>There are a few methods that we can use to listen for transition updates (when a transition started, completed, triggered etc..) and in our case we’d like to listen to the transition completed (<strong>onTransitionCompleted</strong>) which we use to fade out the entire motion layout view component (including all children views) The code below shows how this can be done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a2c8a4e3480d436aab4122698f682a/href">https://medium.com/media/f9a2c8a4e3480d436aab4122698f682a/href</a></iframe><p>As you can see, at the end of a transition, <strong>onTransitionComplete()</strong> callback is invoked by the Android system, in which we can perform post transition operations. In our case, we plan to run another animation to slowly fade away the delete image view (for a duration of 250ms) and show a toast message saying “Message deleted!” at the end of that animation. The above code shows exactly this.</p><p>In summary, MotionLayout helps us build complex view motions based on user interactions, while automatically reversing that motion, all out of the box!</p><p>I hope you found this article helpful! Please leave any questions/comments below. Also I would love to hear how MotionLayout is helping your app screens become lively!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a80fd06401c" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/building-swipeview-using-motionlayout-7a80fd06401c">Building SwipeView using MotionLayout</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Kotlin Coroutines]]></title>
            <link>https://balarkav.medium.com/introduction-to-kotlin-coroutines-5a4a17f365cf?source=rss-f164f3664db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a4a17f365cf</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Balarka Velidi]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 23:35:00 GMT</pubDate>
            <atom:updated>2020-03-18T23:35:00.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i75IsRQO25E5Uz00" /><figcaption>Photo by <a href="https://unsplash.com/@amir_v_ali?utm_source=medium&amp;utm_medium=referral">amirali mirhashemian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Brief History:</p><p>Google made a huge announcement in its I/O ’19 conference that Kotlin will be supported as first class language for Android development. Along with that, it introduced Coroutines in Kotlin to make asynchronous, non-blocking programming intuitive and performant. Since then coroutines has become very popular, very fast in Android developer community. Coroutines by themselves aren’t new to computer programming. They were referred to as programming components to represent subroutines for multitasking during assembly programming days.</p><p>Why another Library for multi-threading?</p><p>In our existing Java/JVM world, we have classic Threads, Executors and other mechanisms to achieve multi-threading. So what is the need for yet another way to create/maintain multiple threads? What are we achieving here that we aren’t able so far?</p><p>In any typical asynchronous programming, the challenge is to coordinate all the parallel executing threads, ensure they are not deadlocked and gather their results after they are done. If you look at any web based programming languages (say Javascript), this is a very common paradigm in which, we invoke a function, not knowing when we get the result from that function, we give that function another function as “callback function” so that it can call this callback function once it is has the result ready. Given a set of asynchronous tasks, that need to happen one after another, this pattern leads into a staircase of callbacks, popularly known as “callback hell”. This problem is not different to any non-web programming languages either, which is one key aspect (among others) that Kotlin Coroutines aims to solve for.</p><p>Coroutines are light weight threads in kotlin. A standard function is a block of code instructions line by line executed and operated on the result of a previously executed instructions. A standard function is a blocking function, meaning the caller has to wait till the function is complete and returns a result for the caller to consume and continue. This is essentially where coroutines differ though. With Coroutines, a function is named as “suspend” that has one or more of body statements running longer to complete, which means, it is not preferred to keep the caller function waiting for this suspend function’s body to complete.</p><p>Let’s take a basic example, where we call the API server to fetch a list of products, and store them in the database. We are looking at 2 operations that are asynchronous in nature and can take many seconds to complete (network fetch, db write).</p><p>Using a standard function, we call the network API first, and once the response is obtained, parse them and write them to the database. However, we need to link the second asynchronous operation with the first by sending it as callback.</p><p>Example:</p><pre>fun fetchProducts() {<br>     api.fetchProducts { jsonResponse -&gt;<br>          val products = parseProducts(jsonResponse)<br>          storeProductsInDB(products)<br>     }<br>}</pre><p>Note, we haven’t considered any error handling logic in the above function, but when added it gets complicated to understand and maintain.</p><p>With Coroutines in action, there is no need for callback, and the 2 asynchronous operations can be written as if they are sequential statements and still achieve the same result as above.</p><p>Below is the coroutine version:</p><pre>suspend fun fetchProducts() {<br>    val jsonResponse = api.fetchProducts() // 1st asynchronous function<br>    val products = parseResponse(jsonResponse)<br>    storeProductsInDB(products) // 2nd asynchronous function<br>}</pre><p>Coroutines in Android:</p><p>Coroutines really shine bright in Android development as well, where the main objective is Main thread safety. In mobile platforms, the UI thread/Main thread is responsible for drawing views on the screen, and responding to the user interactions and is super busy all the time constantly running in a loop and dispatching actions based on user events. Making the main thread to work on any longer tasks is anti-pattern that leads to a lag/jitter in the UI responsiveness and must be avoided at all costs. So, how does a User interface screen load the data from server and show it to the screen you may ask? This is done by creating a new thread (say I/O thread) from Main thread, make the API call on that I/O thread and once the API response is fetched, switch to the main thread and render the data on the screen!</p><p>This is where Kotlin coroutines come in handy! Coroutines come with a context/scope in which a certain action can be performed and here the scope will be based on where the suspend function is triggered. For example: when triggered inside activity the scope is Main thread, and once a new scope is created inside the coroutine, it changes to that locally created scope and continue the work.</p><p>Thanks for reading! Hope you will experience the joy of writing coroutines as I did!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a4a17f365cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>