<?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 Mayank Mehta on Medium]]></title>
        <description><![CDATA[Stories by Mayank Mehta on Medium]]></description>
        <link>https://medium.com/@Mayank_Mehta?source=rss-f4f1a3af6df5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hTGbxEG7x5qq3IBL.jpeg</url>
            <title>Stories by Mayank Mehta on Medium</title>
            <link>https://medium.com/@Mayank_Mehta?source=rss-f4f1a3af6df5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:46:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Mayank_Mehta/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[App Attestation with Play Integrity : Token Decryption and Decisioning (Part 2)]]></title>
            <link>https://medium.com/@Mayank_Mehta/app-attestation-with-play-integrity-token-decryption-and-decisioning-part-2-277727cd316c?source=rss-f4f1a3af6df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/277727cd316c</guid>
            <category><![CDATA[play-integrity-api]]></category>
            <category><![CDATA[attestation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile-security]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mayank Mehta]]></dc:creator>
            <pubDate>Fri, 10 May 2024 13:01:25 GMT</pubDate>
            <atom:updated>2024-05-10T13:04:56.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LkIurrghJkfgwJ7f" /><figcaption>Photo by <a href="https://unsplash.com/@calina?utm_source=medium&amp;utm_medium=referral">Georg Bommeli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>App Attestation with Play Integrity : Token Decryption and Decisioning (Part 2)</h3><p>In <a href="https://medium.com/@Mayank_Mehta/app-attestation-with-play-integrity-verdicts-for-multi-point-inspection-part-1-199357ce64c9">Part 1</a> of the series, we learned about App Attestation, how to generate an integrity token, and what verdicts are baked in the token. In this last part of the series, we’ll learn how to safely decrypt the token, validate it, and make a business decision.</p><p>Essentially, after we’ve generated an integrity token for a given user’s action in the application itself. We would send the integrity token to our secure server (attestation service) along with the API request that we want to protect.</p><p><strong>Responsibilities of an Attestation Service</strong></p><ul><li>Obtaining OAuth 2.0 access token to consume <a href="https://console.cloud.google.com/">GCP</a> resources.</li><li>Decrypting integrity token with Google Play Integrity API.</li><li>Message integrity and replay protection checks.</li><li>Decision based on verdicts.</li><li>Refreshing access token.</li></ul><blockquote>⚠️ Never cache integrity tokens or it’s verdicts.</blockquote><p><strong>Sequence diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWparwBzS9jDN4VUYP8Dag.png" /></figure><p><strong>Step 1 and 4</strong>:</p><p>Google provides OAuth 2.0 <a href="https://developers.google.com/identity/protocols/oauth2#libraries">libraries</a> in a variety of languages to interface with Google’s Identity Provider. This blog article will focus on how to utilize Service Account keys to obtain an access token. At the conclusion of the blog article, I have included thorough steps with screenshots on how to set up project and service accounts.</p><p>You can download a service account key in json format from Google Cloud Project, as shown below, and yes, they contain the private_key and client_id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4c6b2bafe21391e028ccffdb38514da/href">https://medium.com/media/e4c6b2bafe21391e028ccffdb38514da/href</a></iframe><p>I used com.google.auth:google-auth-library-oauth2-http:1.20.0 java library to do the following:</p><ol><li>Generate and sign JWT using my service account key.</li><li>Fetch access token.</li></ol><blockquote>⚠️ If you are using Service account keys for OAuth 2.0 (server to server), it is important to have a play book to rotate keys at regular cadence.</blockquote><blockquote>Have contingency plan incase keys are compromised.</blockquote><blockquote>Host your keys on secure server.</blockquote><p><strong>Step 5:</strong></p><p>Client app is responsible for generating a new integrity token for every high risk user action we want want to protect. We have covered this in <a href="https://medium.com/@Mayank_Mehta/app-attestation-with-play-integrity-verdicts-for-multi-point-inspection-part-1-199357ce64c9">previous</a> blog post.</p><p><strong>Step 6 to 9:</strong></p><p>The OAuth 2.0 access token that our app attestation service obtained from Steps 1–4 will be used to call the GCP Play Integrity API to decode the token. Additionally, our service will be responsible for periodically refreshing access tokens.</p><p>Example of the request would look like below:</p><pre>curl  -X POST \<br>  &#39;https://playintegrity.googleapis.com/v1/com.example.package:decodeIntegrityToken&#39; \<br>  --header &#39;Accept: application/json=v1&#39; \<br>  --header &#39;Authorization: Bearer *redacted*&#39; \<br>  --header &#39;Content-Type: application/json&#39; \<br>  --data-raw &#39;{ &quot;integrity_token&quot;: &quot;*redacted*&quot; }&#39;</pre><blockquote>🌟 I suggest writing your own logic to handle replay protection, as Google appears to allow retrying the same integrity token a few times.</blockquote><p><strong>Step 10:</strong></p><p>Depending on the business use case / user behavior that you are safeguarding using Play Integrity, it is important to create a scenario of consequence based on verdict analysis.</p><p><strong>Step 11:</strong></p><p>In production it would be ideal <strong>not </strong>to sent integrity verdicts back to mobile client :) Just decision should suffice.</p><p><strong>Google cloud project setup, API access and credentials creation</strong></p><ol><li>New project creation on <a href="https://console.cloud.google.com/">Google Cloud</a></li></ol><figure><img alt="Project setup" src="https://cdn-images-1.medium.com/max/1024/1*zYvu-DaujKF0IcxIAdTKDQ.png" /></figure><p>2. Enabling Google Play Integrity API for your cloud project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkAot5cIScnEYQzILBK63Q.png" /></figure><p>3. Service account creation with roles</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlC2wpKy9wVj2-vI2I9S1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57p98UI7_0acRM-98PBkaA.png" /></figure><p>4. Generate service account key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pfl7cdabCKpc0J2qnewpsA.png" /></figure><p>5. Link the GCP project with your application in play store.</p><p>If you’ve gotten this far, I appreciate it and hope you learned something. This finishes the App Attestation series; please share your experiences with adding this to your app. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277727cd316c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App Attestation with Play Integrity: Verdicts for Multi-Point Inspection (Part 1)]]></title>
            <link>https://medium.com/@Mayank_Mehta/app-attestation-with-play-integrity-verdicts-for-multi-point-inspection-part-1-199357ce64c9?source=rss-f4f1a3af6df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/199357ce64c9</guid>
            <category><![CDATA[mobile-security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[attestation]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[play-integrity-api]]></category>
            <dc:creator><![CDATA[Mayank Mehta]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 13:38:22 GMT</pubDate>
            <atom:updated>2024-02-01T13:38:22.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hh2fsVUCifbap9e5" /><figcaption>Photo by <a href="https://unsplash.com/@kenziem?utm_source=medium&amp;utm_medium=referral">Mackenzie Marco</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this two-part series, we’ll go over how to leverage Google’s Play Integrity API for app attestation. In part one, we will discuss why we should invest in app attestation, how to generate an Integrity Token, why Message Integrity is crucial, and finally how to interpret Integrity Token verdicts.</p><h4>Why should you learn about App Attestation?</h4><p>In a world where we are focused on launching customer-facing features to get the competitive edge and lock user’s attention, it is equally important to invest in non-ui features to keep our customers safe. Lets run through few questions, would we like that our customers are:</p><ol><li>Interacting with a genuine app binary that is recognized by Google Play?</li><li>Running the app on a genuine Android device powered by Google Play services / games?</li><li>Running the app on a device that does not have malware/harmful apps?</li></ol><p>If you answered YES to any of the questions above, this series of articles will explain how we can leverage the Play Integrity API to keep our consumers safe.</p><h4><strong>How does this work?</strong></h4><p>We have two components to consider:</p><ol><li><a href="https://maven.google.com/web/index.html#com.google.android.play:integrity">Play Integrity Android Library</a>: In the app we will use this library to generate an Integrity Token (which is encrypted) to protect a user action. We will send this token to our server along with the request we are trying to protect.</li><li>In our secure server — we would decrypt the Integrity Token, either locally (by self managed keys) or by making calls to Google Play Integrity <a href="https://console.cloud.google.com/marketplace/product/google/playintegrity.googleapis.com">API</a> . Once a token is decrypted we get a JSON response that has verdicts, we will verify the information and make a decision on how we want to handle the request.</li></ol><blockquote>Apple has a similar concept of <a href="https://developer.apple.com/documentation/devicecheck/establishing_your_app_s_integrity">App Attestation</a>, however Android Play Integrity Token verdicts are comprehensive and help make an educated decision.</blockquote><h4><strong>Integrity Token Generation</strong></h4><p>The Play Integrity Android Library offers two options for creating Integrity Tokens: Standard Request and Classic Request. Depending on the use case, we might select any request type. The following pros and cons for each request type will help you make an informed selection.</p><p><strong>Standard Request:</strong></p><p>Pros:</p><ol><li>Low latency.</li><li>To optimize, we can initialize the token provider during app launch and generate a new token on demand for each user action we wish to protect.</li><li>Only token decryption counts toward the project’s rate limit</li></ol><p>Cons:</p><ol><li>Some verdicts could be cached. Compromise for low latency.</li><li>The request hash limit is 500 bytes.</li><li>Token decryption requires making a call to Google Cloud Play Integrity API. It creates a hard dependency on an external service.</li></ol><p><strong>Classic Request:</strong></p><p>Pros :</p><p>1. All verdicts are re-computed.</p><p>2. Token decryption can be done on our secure server. However, we would be responsible for securing decryption and signature validation keys. While this is an option, Google recommends to get the token decrypted using its API.</p><p>Cons:</p><p>1. High latency and expensive (in terms of data and battery usage).</p><p>2. Should be used for one-off checks.</p><p>3. Token generation and decryption is counted towards the project’s rate limit.</p><blockquote>🛑 Play Integrity API has a 10K rate limit for total request per day for each app. You can submit an intake request<a href="https://support.google.com/googleplay/android-developer/contact/piaqr"> here</a> to be considered for higher rate limit tier.</blockquote><h4><strong>Message Integrity and Replay Protection</strong></h4><p>The fundamental principle of message integrity is to ensure that our request is not tampered with, while it gets sent from our client to the server. When we generate an integrity token, we should associate it with elements of the request that we are protecting with the integrity token.</p><p>With replay protection, we ensure that an integrity token is not replayed from the same device, another device, or for a different request.</p><p>The code example below demonstrates how to associate a request with an integrity token using a standard token provider.</p><pre>standardIntegrityTokenProvider.request(<br>        StandardIntegrityTokenRequest.builder()<br>            .setRequestHash(requestHash)<br>            .build()<br>    )</pre><p>On our backend service, after decrypting the token, we perform a message integrity check on the incoming request by calculating the hash and comparing it to the request hash returned in the decrypted integrity token.</p><blockquote>🤝 Clients and the backend service must agree on which fields will be included in the request hash and how the hash will be generated.</blockquote><p>Things to consider while creating a request hash:</p><ol><li>The play integrity API has a 500 bytes limit on request hash size for Standard Requests. As a result, instead of hashing the entire request, specific attributes from it may be looked at.</li><li>Consider binding some device specific information such that the token is not replayed from another device.</li><li>To provide replay protection, a nonce (number used only once) can be added.</li></ol><blockquote>🤞 The Request Hash that we pass to the Token Provider should NEVER contain information in plain text.</blockquote><p>Google Play Integrity API offers replay protection. As is, if the same token is decrypted several times, it will return an empty response. Based on our risk tolerance, we may need to create our own replay protection for tighter controls.</p><h4>Integrity Token Verdicts</h4><p>The play integrity token gives a comprehensive collection of verdicts from which we can make decisions based on our risk profile. The decrypted integrity tokens contain the following response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d582b3f930dfe64cbb0d775cafda50ea/href">https://medium.com/media/d582b3f930dfe64cbb0d775cafda50ea/href</a></iframe><p>Let us have a brief look at how each particular check should be used.</p><p>1. Request Details: This field can be used to ensure that the request is coming from the app that requested attestation, as well as to check message integrity by utilizing the request hash and time stamp to determine whether the token is stale.</p><p>2. App Integrity: This field can be used to check whether the app is recognized by Google Play.</p><p>3. Device Integrity: This field can be used to identify whether the app is running on a device that supports Google Play services, whether the device passes the integrity check (no API hooking or rooting), whether the device is running a recognized Android version, and whether the device has hardware-backed boot integrity.</p><p>4. Account Details: This field can be used to establish whether the software was purchased or installed via Google Play.</p><p>5. Environment Details (Optional): This field can be used to see if Play Protect is enabled and whether the scan discovered any harmful or risky apps.</p><blockquote>💡 Integrity Token verdicts (after decrypting the token) follow the same structure for both standard and classic request types.</blockquote><blockquote>Optional fields within token verdicts can be configured for each application on Google Play Console.</blockquote><p>If you’ve made it this far, thank you, and I hope you learned something. In Part 2, we’ll go over how to create our backend attestation service to decode the integrity token. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199357ce64c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutines: Context, Cancellation, SupervisorJob scenarios (Part 1)]]></title>
            <link>https://medium.com/@Mayank_Mehta/coroutines-context-cancellation-supervisorjob-scenarios-part-1-95537debab69?source=rss-f4f1a3af6df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/95537debab69</guid>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Mayank Mehta]]></dc:creator>
            <pubDate>Fri, 22 May 2020 17:27:13 GMT</pubDate>
            <atom:updated>2020-05-23T05:15:45.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mNxvFS9RWqMtj7w0cdI8Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rodlong?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rod Long</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article is inspired from amazing <a href="https://youtu.be/w0kfnydnFWI">talk</a> about Coroutines given by <a href="https://medium.com/u/3b5622dd813c">Manuel Vivo</a> and <a href="https://medium.com/u/d5885adb1ddf">Florina Muntenescu</a> during KotlinConf 2019, this is mainly for improving my understanding of the concepts explained in the talk.</p><p>In this article you will find reference to images from the talk and video link at that point in time. Code samples are various scenarios that I came across during the talk and I have added logs for more clarity. Feel free to modify the code and run in Kotlin <a href="https://play.kotlinlang.org/">Playground</a>.</p><h4>Recap from the talk</h4><p><em>CoroutineScope</em> are used for: <br>1. Keep track of coroutines<br>2. Ability to cancel ongoing work<br>3. Notify when failures happen</p><p><em>Job</em> is used for: <br>1. Provide Lifecycle<br>2. Coroutine hierarchy</p><p>Job<em> lifecycle properties</em>:<br>1. isActive<br>2. isCompleted<br>3. isCancelled</p><h4>CoroutineContext: Parent Vs Coroutine</h4><p>To create an instance of CoroutineScope you need to provide CoroutineContext. To create an instance of CoroutineContext you can provide it set of Elements which are Dispatchers, CoroutineName, Job and CoroutineExceptionHandler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XXh6h2ATO-2LneHwtpOwQ.png" /><figcaption>Source: <a href="https://youtu.be/w0kfnydnFWI?t=402">https://youtu.be/w0kfnydnFWI?t=402</a></figcaption></figure><p>Coroutines launched using parent scope will get all elements except Job from parent context. However, inherited elements could be easily overridden as shown in the following code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FFy-rB9waR%3Ffrom%3D9%26to%3D36&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FFy-rB9waR%3Ffrom%3D9%26to%3D36&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d144c3955befc13e15e3ad7812b21d/href">https://medium.com/media/52d144c3955befc13e15e3ad7812b21d/href</a></iframe><h4>Coroutine cancellation</h4><p>As best practice, cleaning up resource is ideal once task is over. Same applies in <em>CoroutineLand</em>. Whenever a coroutine is cancelled it throws CancellationException which when propagated to parent would consider this as handled exception and would take no further action.</p><p>Use following table as reference to various coroutines lifecycles states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUnLhpayGXthDJ8dOB-U3w.png" /><figcaption><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/Job.kt#L35">https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/Job.kt#L35</a></figcaption></figure><p>1. When parentScope is cancelled, all children will get cancelled.</p><p>Here children being all coroutines launched using parentScope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEM4wG84SRv2FnKmpC-o5g.png" /><figcaption>Source <a href="https://youtu.be/w0kfnydnFWI?t=474">https://youtu.be/w0kfnydnFWI?t=474</a></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F4E9S-ZauZ%3Ffrom%3D20%26to%3D24&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F4E9S-ZauZ%3Ffrom%3D20%26to%3D24&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d010d8adbbdc8d1961755a3c4149659/href">https://medium.com/media/8d010d8adbbdc8d1961755a3c4149659/href</a></iframe><p>Once parentScope is cancelled you can’t launch new coroutines using that scope.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FpFWnLxIZX%3Ffrom%3D18%26to%3D24&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FpFWnLxIZX%3Ffrom%3D18%26to%3D24&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f4c41d2bf4be1780ed0b7dd467a3908/href">https://medium.com/media/4f4c41d2bf4be1780ed0b7dd467a3908/href</a></iframe><p>If you want to cancel just the children and not the parentScope you can do the following</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FR5EXlDFlR%3Ffrom%3D22%26to%3D27&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FR5EXlDFlR%3Ffrom%3D22%26to%3D27&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/7039b11b20bd06ad4c2fc4826421c5a2/href">https://medium.com/media/7039b11b20bd06ad4c2fc4826421c5a2/href</a></iframe><p>2. When child Job is cancelled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFtNVgnB3BHjgvASrindiQ.png" /><figcaption><a href="https://youtu.be/w0kfnydnFWI?t=537">https://youtu.be/w0kfnydnFWI?t=537</a></figcaption></figure><ul><li>Siblings are not cancelled</li><li>parentScope is not cancelled</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FHdmZ6QuRp%3Ffrom%3D17%26to%3D17&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FHdmZ6QuRp%3Ffrom%3D17%26to%3D17&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/792d29f9b8a9c828807c1dc691fd4f6a/href">https://medium.com/media/792d29f9b8a9c828807c1dc691fd4f6a/href</a></iframe><p>3. When join is called after Job is cancelled</p><ul><li>It suspends unless cancelled Coroutine is completed.</li></ul><p>4. Can’t await on cancelled coroutine</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2Flqysj5pGQ%3Ffrom%3D20%26to%3D21&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2Flqysj5pGQ%3Ffrom%3D20%26to%3D21&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e91552a132443f96eafcbec897b4bef/href">https://medium.com/media/2e91552a132443f96eafcbec897b4bef/href</a></iframe><p>All suspending function provided in kotlinx.coroutines library support cancellation. Code snipped in this section use delay so they get cooperative cancellation for free.</p><p>Read Kotlin <a href="https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#cancellation-is-cooperative">docs</a> to understand how to write coroutines that supports cancellation.</p><h4>CoroutineExceptionHandler</h4><p>In previous sections we discussed about coroutine cancellation, here we will focus on what happens when coroutines throws unexpected Exceptions. How can they be caught and what happens to CoroutineScope.</p><ol><li>When CoroutineScope uses default CoroutineExceptionHandler</li></ol><p>Default CoroutineExceptionHandler ignores CancellationException, on any other Exception does the following</p><ul><li>Sibling Jobs will get cancelled. parentScope will get cancelled and Exception would be propagated up.</li><li>If Exception is thrown from launch it will crash your application</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F0p62iFibT%3Ffrom%3D9%26to%3D16&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F0p62iFibT%3Ffrom%3D9%26to%3D16&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/dac34c6fae2401069ab8f046ea2b671d/href">https://medium.com/media/dac34c6fae2401069ab8f046ea2b671d/href</a></iframe><ul><li>If Exception is throw from async it will not crash your application unless await is called.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FJvJKfwMFax%3Ffrom%3D10%26to%3D17&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FJvJKfwMFax%3Ffrom%3D10%26to%3D17&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/5623fea7f72e3b716d73285a17b26628/href">https://medium.com/media/5623fea7f72e3b716d73285a17b26628/href</a></iframe><p>2. When CoroutineScope is provided custom CoroutineExceptionHandler</p><ul><li>If Exception is thrown from launch it will not crash your application</li><li>However, parentScope will get cancelled.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FngS1uyz6o%3Ffrom%3D5%26to%3D17&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FngS1uyz6o%3Ffrom%3D5%26to%3D17&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa2d8dffc847aa6b8d01e15510ac151c/href">https://medium.com/media/fa2d8dffc847aa6b8d01e15510ac151c/href</a></iframe><p>3. Child coroutine gets CoroutineExceptionHandler</p><p>In the following code, parentScope is created with custom CoroutineExceptionHandler and when inner coroutine throws an Exception it is caught. Refer back to first section in this post.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FgBQV3w_Mj%3Ffrom%3D9%26to%3D19&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FgBQV3w_Mj%3Ffrom%3D9%26to%3D19&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/21bc0c45b83e108c2f437ff3b9420ecc/href">https://medium.com/media/21bc0c45b83e108c2f437ff3b9420ecc/href</a></iframe><p>4. Don’t break the chain</p><p>Following code will crash the application even though it is launched with custom CoroutineExceptionHandler reason being when Exception is thrown from inner coroutine it will propagate the Exception to its parent which in following code does not how to handle it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FyRKi-dMbM%3Ffrom%3D9%26to%3D18&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FyRKi-dMbM%3Ffrom%3D9%26to%3D18&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ea08d6925bce88cfe1fa0bdeb439caa/href">https://medium.com/media/4ea08d6925bce88cfe1fa0bdeb439caa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnFNYnPB7Y-MHEKSQQEJPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@simmerdownjpg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jackson Simmer</a> on <a href="https://unsplash.com/s/photos/chain-broken?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>SupervisorJob</h4><p>CoroutineScope that needs to survive when child Job fails should have its CoroutineContext created with SupervisorJob and customCoroutineExceptionHandler.</p><ol><li>CoroutineScope is created withSupervisorJob but withoutCoroutineExceptionHandler</li></ol><p>Following code will crash your android application since the exception is not handled and parentScope does not haveCoroutineExceptionHandler.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F7AOHXL5B3S%3Ffrom%3D9%26to%3D16&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F7AOHXL5B3S%3Ffrom%3D9%26to%3D16&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff8649d5ebc2a6dae0bb3e573cfa151/href">https://medium.com/media/5ff8649d5ebc2a6dae0bb3e573cfa151/href</a></iframe><p>2. CoroutineScope is created withSupervisorJob and CoroutineExceptionHandler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5bQpVHXMquFKWUT2eQZpQ.png" /><figcaption><a href="https://youtu.be/w0kfnydnFWI?t=1427">https://youtu.be/w0kfnydnFWI?t=1427</a></figcaption></figure><p>In this sample code when Job1 fails with an Exception</p><ul><li>parentScope and siblings Jobs would not be cancelled.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FB2OibKIPD%3Ffrom%3D9%26to%3D17&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FB2OibKIPD%3Ffrom%3D9%26to%3D17&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" width="800" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a864b0dc7b0d018114bb3c49d7cb765/href">https://medium.com/media/6a864b0dc7b0d018114bb3c49d7cb765/href</a></iframe><p><em>Thank you for reading, Happy Coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95537debab69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coordinator Pattern in Android with Kotlin Coroutines]]></title>
            <link>https://medium.com/capital-one-tech/coordinator-pattern-in-android-with-kotlin-coroutines-fcdf79a089de?source=rss-f4f1a3af6df5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcdf79a089de</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coordinator-pattern]]></category>
            <dc:creator><![CDATA[Mayank Mehta]]></dc:creator>
            <pubDate>Wed, 15 May 2019 17:01:53 GMT</pubDate>
            <atom:updated>2019-05-15T17:01:53.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pIGvQs9IVFttDQs8" /></figure><p>At Capital One, my team builds Android SDKs for the enterprise. Recently we encountered an interesting situation where the UI Flow had to be dynamic, meaning every interaction with the server would return a response containing the next screen the SDK needed to display. We knew this problem could easily result in bad code if not designed well. So, we turned to an approach that responds dynamically to API responses, inspired by Hannes Dorfmann’s Coordinator <a href="http://hannesdorfmann.com/android/coordinators-android">pattern</a>.</p><p>To give some context, our SDKs are built using an in-house Model-View-Intent (MVI) framework. The framework is designed using redux <a href="https://redux.js.org/introduction/three-principles">principles</a> and supports structured concurrency.</p><p>This article focuses on our approach to solve dynamic navigation using Kotlin coroutines.</p><p><em>If you’re unfamiliar with coroutines, </em><a href="https://medium.com/@elizarov"><em>Roman Elizarov</em></a><em> has numerous articles and videos that explains the concept extremely well.</em></p><h3><strong><em>A Coroutines-Based </em>Solution</strong></h3><p><em>Coordinators contain business logic to navigate between views.</em></p><p>A coordinator uses a <strong>coroutine</strong> <strong>actor</strong> that processes asynchronous <strong><em>intentions </em></strong>sequentially and these are <strong>scoped</strong> to a flow’s lifecycle.</p><h4><strong>Components</strong></h4><p>The following diagram is a reference to various components we will be discussing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*Oq55RBh_NKH9LFxn" /></figure><ul><li>Root Coordinator is scoped to the <em>application’s / SDK’s </em>coroutine context and is responsible for invoking a specific flow coordinator based on the business rule via Root Navigator.</li><li>Flow Coordinator is scoped to the <em>activity view model</em> and is shared with all child view models. Basically, they own the responsibility to navigate between views within the flow.</li><li>Flow Navigator is a stateless component that only owns logic for adding views/fragments to the flow’s activity. They are invoked by the flow coordinator.</li></ul><h3>Coordinator</h3><p>The below code example represents a coordinator that is used in Sign In activity flow which is started by Root Coordinator. To keep this article short and focused we will be discussing only one of the coordinators since they all follow similar design principle.</p><h4><strong><em>Constructor</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k_TG2rOlDP8XlZAj" /></figure><p><em>scope</em> is tied to main activity’s view model and shared across child fragment view models. The onFlowComplete lambda is provided by RootCoordinator which should be invoked when a flow is finished. This way, exit and entry of flow is controlled by RootCoordinator.</p><h4><strong><em>Intentions</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dZbzZcNjYtFfVDgQ" /></figure><p>These are what our coordinator consumes to compute an outcome. They could be created by a user action or some async operation like an API response.</p><h4><strong><em>Actor</em></strong></h4><p><em>An actor that can win an Oscar in the async programming world ;)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wVfsGsSPY-8QmB0W" /></figure><p>Our coordinator also has an actor that would be initialized lazily and with an unlimited channel capacity. The capacity we selected is based on our use case since we did not want to drop any intentions. An actor processes intentions sequentially and computes new states via the copy(…) extension function, thus making sure concurrent state mutation does not happen. Ideally, each intention would map to a navigation action that is provided by SignInFlowNavigator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*eK0cLOPTAIJEAN8n" /></figure><p>Coordinator also exposes a function to add intentions to actor’s queue.</p><p><em>More about coroutine actors can be read </em><a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/shared-mutable-state-and-concurrency.md#actors"><em>here</em></a><em>.</em></p><h3>Navigator</h3><p>Now let’s look at the navigator that is used in Sign In activity flow which is invoked by Sign In Coordinator. To keep this article short and focused we will be discussing only one of the navigators since they all follow similar design principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xeQoFTWDcproQ7N-" /></figure><p>Navigators are stateless and have similar scope to that of SignInFlowCoordinator , although they own no business logic. Like coordinator, it processes its intentions via an actor. As you may have noticed, we also pass in an activityFetcher which exposes CompletableDeferred&lt;AppCompatActivity&gt; that navigator suspends on while the activity is not available or is not in a valid lifecycle state.</p><h3><strong>Conclusion</strong></h3><p>The approach discussed above is just one possible implementation of the Coordinator concept. This approach can help make view models and activity/fragments lighter, remove duplication, and abstract navigation logic.</p><p>My team is hiring <a href="http://bit.ly/2WpFABZ">Android developers</a>. If you know anybody who might be interested please send them the link and introduce <a href="https://www.linkedin.com/in/mehtamayank/">me</a> to them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcdf79a089de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/capital-one-tech/coordinator-pattern-in-android-with-kotlin-coroutines-fcdf79a089de">Coordinator Pattern in Android with Kotlin Coroutines</a> was originally published in <a href="https://medium.com/capital-one-tech">Capital One Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>