<?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 Jitin Sharma on Medium]]></title>
        <description><![CDATA[Stories by Jitin Sharma on Medium]]></description>
        <link>https://medium.com/@jitin-sharma?source=rss-d5b7562e9257------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*cUAHMo_fAmNFhaLpToa3-Q.png</url>
            <title>Stories by Jitin Sharma on Medium</title>
            <link>https://medium.com/@jitin-sharma?source=rss-d5b7562e9257------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:05:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jitin-sharma/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[Two targets, one arrow: Cutting down our app size and startup time on Android]]></title>
            <link>https://medium.com/gojekengineering/two-targets-one-arrow-cutting-down-our-app-size-and-startup-time-on-android-eb1eca6ba4ee?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb1eca6ba4ee</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 05:42:27 GMT</pubDate>
            <atom:updated>2022-02-25T05:42:27.401Z</atom:updated>
            <content:encoded><![CDATA[<h4>As the Gojek app scaled, so did the app size. Our teams got together to improve app performance. Here’s how it went.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXoK4m9pIEWyb__M_8rdMg.png" /></figure><p>Gojek helps millions in Southeast Asia to get to places, satiate hunger, send payments, and much more. Needless to say, building and maintaining such a huge ecosystem is no easy job. 😅</p><p>Over time as we scaled, our app size had increased considerably as well. Early last year, we started out a project where all of our mobile engineering teams came together to improve app performance in general. Here’s the story.</p><h3>App size worries</h3><p>Our app size was touching ~90 MB and had not shown any kind of downward trend in the last few months. To fix this, we started by looking at duplicate/unused libraries, images as well as optimising PNGs which gave us 5–6 MBs of reduction.</p><p>All of our apps inherit a singular design system called Aloha, which has an illustration system to provide region aware images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GCSPaBMcLapUkv3y.png" /></figure><blockquote><em>Illustrations are context aware images which may change according to region. A default static set is shipped as vector drawables on Android.</em></blockquote><p>While the Design System Library ships with a large set of illustrations, only a subset of it is used with each application. We discovered that our consumer facing app was not using close to 600 of these, but they were being packaged in the .apk. This was particularly puzzling since we have code and resource shrinking in place for our release apps.</p><p>We calculated that we can easily save ~4MB on app size by removing these unused assets. Little did we know the rabbit hole we were getting into 😬</p><h3>Wrangling code minification</h3><p>We started debugging why unused vector drawables for these illustrations aren’t getting deleted. We use<a href="https://www.guardsquare.com/dexguard"> Dexguard</a> for obfuscation and minification. Dexguard is paid version of widely used Proguard tool(now replaced by R8).</p><p>Upon a closer look we found this rule</p><pre>-keepresources drawable/default_**</pre><p>Since all of our drawables start with default_ prefix, removing this rule should have fixed our problems. We removed this rule but unfortunately all unused drawables were still in the apk.</p><p>After countless cycles of changing rules and CI builds 😬, we stumbled upon this in our CI build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QEp4dfOpytkQbakh.png" /></figure><p>If you look closely at build output, the number of resources before and after minification are identical, which means resource minification isn’t happening at all. Classes were still getting minified so the whole process wasn’t broken. We recognised that we found a much larger problem at play than what we started with.</p><p>We started talking to Dexguard engineers and took a much stricter look at our rules as well as rules being inherited from libraries integrated in our project. Finally we found these faulty rules</p><pre>-keep class **.R<br>-keep class **.R$* {<br>    &lt;fields&gt;;<br>}<br>-keepclassmembers class **.R$* {<br>    public static &lt;fields&gt;;<br>}</pre><p>Since these are wildcard rules on generated R.class file, they would end up keeping all R class references irrespective of packages. R classes reference resources directly (R.drawable), so presence of these files caused Dexguard to not delete any resource at all!</p><p>We found these rules being inherited from 3 libraries, 2 internal and 1 external. We reached out library authors and got these rules fixed. Finally we built our app with rules and got hit with new surprises. 😂</p><ol><li>Our app size reduced by ~17 MB instead of ~4MB we were looking at initially 🙂</li><li>Unused drawables which we wanted to delete were still present in the apk 🙈</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*2Hbc7DW_tUbSLPdz.gif" /></figure><p>So, what actually happened?</p><h3>Transitive R classes</h3><p>If you have developed Android apps, you have probably used R. references all over your code base. These nifty references are auto generated as soon as a resource is added and allow you to access them in your code.</p><p>R class references are generated at various levels — for your third party libraries, your modules and then finally your app module. At each point of integration whether you are adding dependency for a third party library in your module or adding dependency of another module, these classes are copied over with duplication from the dependency, and it happens over and over again, until the app module. Here’s a graphical representation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GuQB5Fflxu7r6gXg.png" /></figure><p>Why you ask, since references are copied over you can reference any resource from dependency using your own package’s R class. Makes it easy, but it takes a toll on the amount of references being created. As the project becomes larger, these references can grow significantly.</p><p>That’s exactly what happened to us, since our project has 200+ modules and hundreds of third party libraries being imported across, our R class references ballooned into millions and to make matters worse, we had a rule which was asking Dexguard not to delete them!</p><p>Now since we fixed the problematic rules, all these unused references got deleted — 2.5 million fields deleted to be exact!</p><p>This is where much of our ~17MB size reduction came from(15MB worth of duplicated references + 2MB of resources they were referring too). Each of these R.class reference is a field and this code gets packaged into a dex file. Dex files have a limit of references it can hold which is 65k. All these irrelevant fields were packaged into multiple dex files which was causing size increase. Dex file count in our apk reduced from 50 to 10!</p><h3>Unused assets</h3><p>While we were happy with all these results, we still didn’t figure out our original problem 😅, unused drawables. After some more email debugging sessions with friendly Dexguard engineers, we found more problematic rules</p><pre>-keep,allowmultidexing class com.gojek.app.package1.** { *; }<br>-keep,allowmultidexing class com.gojek.app.package2.** { *; }<br>-keep,allowmultidexing class com.gojek.app.package3.** { *; }</pre><p>We found wildcard rules for module package names, which would cause R.class references for these modules to be kept by Dexguard. Since our Design System library was a dependency of all these modules, they were copying over all drawables references which would then not get deleted, causing all those drawables files to not get deleted as well.</p><p>Once we fixed these rules, our unused assets started getting deleted as well giving us another 4MB of size save. Overall we reduced ~21MB of app size with this exercise 🚀</p><h3>Performance implications</h3><p>Once we realised our dex count had reduced by 40, we started benchmarking new builds. Dex files are loaded directly while the app starts especially on fresh launches so we expected to see some improvements in application load time. Since we had to benchmark release builds and check how fast the OS itself is loading our application, our options were limited on what we could use. We captured <a href="https://developer.android.com/topic/performance/tracing/command-line">systrace</a> on various devices and then visualised it on <a href="https://ui.perfetto.dev/">Perfetto UI</a>.</p><p>Our local tests confirmed that fresh launches became 30–50% faster on certain devices, but since dex files often get compiled and optimised over time on device, we didn’t expect such metric from production.</p><p>Eventually we got ~20% reduction in slow app launch metric on Android vitals after the new release was adopted by the majority of our users 😀. Our ANRs also suspiciously went down in that release.</p><h3>End notes</h3><p>This whole exercise was extremely adventurous and yet it was a reminder of what kind of bugs may lie in your source code. If you’ve reached here, I can leave you with following points of caution</p><ul><li>Keep an eye on proguard rules being imported by libraries. You can easily check them by adding -printconfiguration in your proguard rule file.</li><li>At all costs, avoid wildcard keep rules, especially at module package level. You might end up keeping far more than intended for.</li><li>Check apk size at pull request branch vs your main branch, a simple foolproof way to avoid size increase scares.</li></ul><p>I also gave a talk on this topic in <a href="https://android-worldwide.com/">Android Worldwide</a> conference. Check out the <a href="https://speakerdeck.com/jitinsharma/relevance-of-code-minification-in-a-performance-world">slides</a> here and video below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjLQ20qA-fh0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjLQ20qA-fh0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjLQ20qA-fh0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b550e75eaaee8e525e0d87cdf2ba701/href">https://medium.com/media/4b550e75eaaee8e525e0d87cdf2ba701/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWwoozDxeKoXMtXEyrtLw.png" /></figure><p><a href="https://www.gojek.io/blog">Here</a> are more stories on how we do what we do.</p><p>Oh, we’re hiring! 👇</p><figure><a href="https://bit.ly/gojekjobsblogs2022"><img alt="" src="https://cdn-images-1.medium.com/max/700/1*c2_eIvR2WDUWnP6YmzcGpQ.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb1eca6ba4ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/two-targets-one-arrow-cutting-down-our-app-size-and-startup-time-on-android-eb1eca6ba4ee">Two targets, one arrow: Cutting down our app size and startup time on Android</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Screenshot Testing our Design System on Android]]></title>
            <link>https://medium.com/gojekengineering/screenshot-testing-our-design-system-on-android-d78c9854eb6b?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78c9854eb6b</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ui-testing]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Tue, 14 Jan 2020 05:11:39 GMT</pubDate>
            <atom:updated>2020-01-14T05:11:39.807Z</atom:updated>
            <content:encoded><![CDATA[<h4>An overview of how we do screenshot tests, and the open source libraries that helped us along the way.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDWU7CE8XeZNDZ0fa4KNLw.jpeg" /><figcaption><a href="http://bit.ly/2Nmjr5A">gojek.jobs</a></figcaption></figure><p>In this post, we’ll take a look at how we test our Design System components on Android using screenshot tests to make them pixel perfect. 👌</p><p>Let’s start with an example.</p><p>Take a look at these two images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GON1POsYNn-n13Yvx9KWlQ.png" /><figcaption>Are these images identical?</figcaption></figure><p>They may look the same, but they aren’t! Here’s what’s different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Cunmda2Ctain_g4xPU3iQ.png" /></figure><p>There are two subtle changes — the colour of the button is a different shade of green and the elevation is also different.</p><p>In <a href="https://blog.gojekengineering.com/ux-engineering-at-gojek-9de2abe24928">Asphalt</a>, our design language system, we want to make sure our UI components are robust and detect breakages early. Here’s how we leveraged screenshot tests to achieve this.</p><h3>Components Everywhere</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UH05mhuGHielEDM4RtbOcQ.png" /><figcaption>Asphalt Components in Gojek app</figcaption></figure><p>With Asphalt, we create components that can be reused across the Gojek app. Every button, text, input, or card which you see in most of the screens of the app is an Asphalt Component. On top of this, we have a demo app which showcases the usage of these components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixxp__0PC20bAMigugixhg.png" /><figcaption>Asphalt Components in Demo app</figcaption></figure><p>Our components are the backbone of the Gojek app UI. For example, our button class has 300+ occurrences across Gojek’s consumer app codebase. This heavy reuse helps us enforce design guidelines across the app. The importance of these components requires that we test them thoroughly, as even a small regression in one component could mean a degraded experience for our users.</p><h3>[U]n[I]t Testing</h3><p>Unit tests are supposed to test logic and fail when expectations aren’t met. How do we expect that a certain UI is being rendered properly?</p><p>The idea of screenshot testing is to have a master copy of screenshots that we know are correct and on every test run compare the current screenshots to the master copy. If the current set does not match the master set, the test fails. This will allow us to check unintentional UI changes. If the changes are intentional, then we run the tests in update mode which updates the master screenshots.</p><p><strong>Here is the high level outline:</strong></p><blockquote>- Write Espresso test for all activities in the demo</blockquote><blockquote>- Take screenshots and create a master set</blockquote><blockquote>- At every CI run take screenshots again and compare with master set</blockquote><p>We started out with <a href="https://github.com/Karumi/Shot">Shot</a>, an open source library which allows us to take screenshots and compare them using gradle commands and generate reports.</p><p>Here’s what a test for our Alert component looks like 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cec820b7a2b3ce9859a2c1cd1df150c/href">https://medium.com/media/5cec820b7a2b3ce9859a2c1cd1df150c/href</a></iframe><h3>Achilles Heel — The Android Emulator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WWyaL1uLibHeXC15.png" /></figure><p>While the Android emulator has improved a lot in recent times, we found running emulators in CI is still unreliable.</p><p>Here are a few issues we faced:</p><blockquote>- We had to wait to for the emulator to start up, which was only possible through a hack(y) script by continuously pinging adb commands</blockquote><blockquote>Emulator would put more memory pressure on CI runners</blockquote><blockquote>Emulators also need hardware acceleration which required us to enable kvm on our Linux-based machines.</blockquote><p>Running Instrumentation test cases with these issues would mean our tests would be flaky — and we couldn’t have that.</p><h3>Firebase Test Lab saves the day!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IIH6x5bWvHn1Gcv_.jpg" /></figure><p>We decide to move away from emulators to real devices.</p><p>One idea was to have devices connected to a machine and use the machine as a runner for running test cases in CI — a device test lab.</p><p>But devices come with their own baggage — maintaining them. They may be interrupted by software updates, system dialogs… or get overcharged and explode! 🔥</p><p>We found the next best thing: <a href="https://firebase.google.com/docs/test-lab">Firebase Test Lab</a> — a set of devices in cloud, managed automatically and available via CLI.</p><p>This solved our device problem, but we ran into another one — Firebase Test Lab doesn’t allow you to run custom gradle commands. Instead, it expects you to upload a debug and a test apk, and it will run the tests for you. This meant we could no longer use Shot for taking screenshots and comparing them 😦</p><p>While scratching our heads over how to overcome this problem, we found that Firebase Test Lab <a href="https://firebase.google.com/docs/test-lab/android/test-screenshots">allows you</a> to take screenshots through a library and then retrieve them from Google Cloud Bucket.</p><p>There is also a <a href="https://github.com/runningcode/fladle/">gradle plugin</a> which automates this process including downloading artifacts from GCP — open source to the rescue again!</p><p>Here’s how our test case looks like with Firebase screenshot library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f495b05694343d32d1c6ec0469e7de40/href">https://medium.com/media/f495b05694343d32d1c6ec0469e7de40/href</a></iframe><p>For image comparison we used <a href="https://imagemagick.org/">ImageMagick</a>, a very popular and feature-packed CLI tool for image manipulation. It also allows us to output a different image in case two images don’t match, which is super useful for generating test failure reports.</p><h3>The final piece — integrating screenshot tests into our developer workflow</h3><p>As part of CI, we do the following things when a merge request is raised:</p><blockquote>- Build the project</blockquote><blockquote>- Run Espresso Tests on Firebase Test Lab</blockquote><blockquote>- Retrieve screenshots and compare them with master set</blockquote><blockquote>- If any screenshot doesn’t match, we fail the build and add a comment to PR using <a href="https://danger.systems/">Danger</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6gb_yARAM4n83umso03Xw.png" /><figcaption>Danger reporting mismatch in screenshot along with diff image.</figcaption></figure><p>We have been using this setup for some time now, and it’s worked out great for us! We have been able to execute multiple UI refactors with high confidence.</p><h3>What’s next?</h3><p>We will continue to invest in this setup in the future. Things like testing localisation, having a test matrix with multiple screen sizes, API levels, device densities… these are some things we have planned for the future.</p><p>A big thank you to the open source libraries that helped us achieve this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yigf1nGxRKjzV7vIC_YkYg.png" /></figure><p>Liked what you read? <a href="https://mailchi.mp/go-jek/gojek-tech-newsletter">Sign up for our newsletter</a> and we’ll send you weekly updates about our stories! 🖖</p><figure><a href="http://bit.ly/2Nmjr5A"><img alt="Gojek Open Positions" src="https://cdn-images-1.medium.com/max/803/1*XSAkmYAomyHp6_18rjjAfA.jpeg" /></a><figcaption>gojek.jobs</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78c9854eb6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gojekengineering/screenshot-testing-our-design-system-on-android-d78c9854eb6b">Screenshot Testing our Design System on Android</a> was originally published in <a href="https://medium.com/gojekengineering">Gojek Product + Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Kotlin Coroutines]]></title>
            <link>https://proandroiddev.com/demystifying-kotlin-coroutines-6fe1f410570b?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fe1f410570b</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 17:58:33 GMT</pubDate>
            <atom:updated>2018-08-05T17:58:33.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiUsTtx2akhgfMeOiV2Ikw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/jGN7JUKZcU0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Artem Kovalev</a> on <a href="https://unsplash.com/search/photos/mist?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Kotlin coroutines offer a new way of asynchronous executions but directly looking at library functions may become a bit confusing.</p><p>In this article, I’ll try to demystify coroutines.</p><p>Let’s start at basic. We have a something called <strong><em>launch</em> </strong>which can be used to launch a coroutine</p><pre><em>private fun </em>myHeavyFunction() {<br>    Log.e(&quot;Thread Running &quot;, Thread.currentThread().<em>name</em>)<br>}<br><em>val </em>job = launch <strong>{ </strong>myHeavyFunction() <strong>}</strong></pre><p>The above snippet represents a very simple way for execute a function asynchronously using <strong><em>launch</em></strong> which returns a <strong><em>Job</em></strong><em>. </em>Job represents a coroutine job which can be cancelled or queried for it’s status.</p><pre><em>override fun </em>onStop() {<br>    <em>if </em>(job.isActive) {<br>        job.cancel()<br>    }<br>}</pre><p>Now if we look at our logs to check at which thread our function was actually running, we get something like this</p><p><strong><em>E/Thread Running: ForkJoinPool.commonPool-worker-2</em></strong></p><p>Our code was running inside a thread where did that come from. Let’s dig a little bit into declaration of <strong><em>launch</em></strong> itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*8ss1tOvxKVFQDAiKlnklGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*dlO3opR1kyiJGUHY7YuB6w.png" /><figcaption>Since Coroutines are multi-platform, we have actual variable for JVM dispatcher</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*uS_pFsKYTTqa2H4MDkAZtg.png" /></figure><p><strong><em>launch</em> </strong>takes <em>CoroutineContext </em>as first parameter which then defaults to DefaultDispatcher which is a CommonPool class which creates a CoroutineContext with Executors based on total number of processors in device. Full source <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-core/src/CommonPool.kt">here</a></p><p>Coroutine Builders like <strong><em>launch</em> </strong>can accept a <strong><em>CoroutineDispatcher</em></strong> which is actually responsible for running code in separate thread.</p><p>We can create our own dispatchers easily.</p><pre><em>val singleThreadDispatcher </em>= newSingleThreadContext(&quot;singleThreadDispatcher&quot;)</pre><p><strong><em>newSingleThreadContext</em></strong><em> </em>is provided by Kotlin coroutines library itself to create a context which will run on just single thread. We can create our own function on top of this</p><pre><em>fun </em>&lt;T&gt; singleThreadAsync(block: () -&gt; T): Job = launch(<em>singleThreadDispatcher</em>) <strong>{ </strong>block.invoke() <strong>}</strong></pre><pre>job = singleThreadAsync <strong>{ </strong>myHeavyFunction() <strong>}</strong></pre><p>And here’s the log</p><p><strong><em>E/Thread Running: singleThreadDispatcher</em></strong></p><p>So we just created our own simple coroutine with our own threading scheme :)</p><p>Let’s see what we can do more with Dispatchers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de725ef0736af4f3a7da9824124aa06d/href">https://medium.com/media/de725ef0736af4f3a7da9824124aa06d/href</a></iframe><p>Here we have created three different dispatchers and using override method <strong><em>dispatch</em></strong><em> </em>we are executing a <strong><em>Runnable</em></strong><em> </em>block in a different way in each one of them -&gt; a simple thread, using RxJava and on Android main thread using Handler.</p><p>If we execute our function using these dispatchers, we get these logs</p><p><strong><em>E/Thread Running: Thread-582<br>E/Thread Running: RxCachedThreadScheduler-1<br>E/Thread Running: main</em></strong></p><p>This really shows the power of coroutines because Coroutines in the end are just language syntax, they have nothing to do with platform which they are running on. That responsibility is delegated to the developer himself using a set of functions, he may execute coroutines as he like on a Rx thread or on the main thread.</p><blockquote>Coroutines are like empty ice-cream cones, it’s upto you which ice-cream you want to fill in them</blockquote><h3>Thread-less Asynchronism</h3><p>Writing asynchronous code is traditionally considered a job for threads which is not always true. Let’s see how we can tackle this using Coroutines</p><p>Let’s consider a sequence of function executions</p><pre>mySmallFunction1() <br>myHeavyFunction() // Takes 3 seconds to execute<br>mySmallFunction2()</pre><pre>//Order<br>E/mySmallFunction1 running on: main<br><strong>E/myHeavyFunction running on: main</strong><br>E/mySmallFunction2 running on: main</pre><p>Now since myHeavyFunction() takes long to execute, we may want to execute it <em>asynchronously.</em></p><pre>mySmallFunction1()<br>thread <strong>{ </strong>myHeavyFunction() <strong>} </strong>//Execution in a separate thread.<strong><br></strong>mySmallFunction2()</pre><pre>//Order<br>E/mySmallFunction1 running on: main<br>E/mySmallFunction2 running on: main<br><strong>E/myHeavyFunction running on: Thread-697</strong></pre><p>Here we moved myHeavyFunction() to a separate thread and executed it <em>asynchronously. </em>But what if</p><pre>mySmallFunction1()<br>launch(<em>UI</em>) <strong>{ </strong>myHeavyFunction() <strong>}<br></strong>mySmallFunction2()</pre><pre>//Order<br>E/mySmallFunction1 running on: main<br>E/mySmallFunction2 running on: main<br><strong>E/myHeavyFunction running on: main</strong></pre><p>Here we executed the heavy function in a Coroutine context(<strong>UI</strong>: provided by coroutine-android library) which is running on main thread. The execution is still <em>asynchronous </em>since Coroutines handle that part through suspend functions but execution still happened on main thread without creating an extra thread.</p><h3>Practically Coroutines</h3><p>In most of the practical we would require a callback from asynchronous execution, so that we can update UI etc. that where <strong><em>Deferred</em></strong> comes in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*l0CMty5WIb93a74kwtrPkQ.png" /></figure><p><strong><em>Deferred</em></strong> itself extends <strong><em>Job </em></strong>but with an additional feature where it can return future values once a function has completed execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28152724655005e0c3d177d686f3c34a/href">https://medium.com/media/28152724655005e0c3d177d686f3c34a/href</a></iframe><p>Let’s see what we did here</p><ol><li>launch(UI) creates a coroutine <strong><em>Job</em></strong> with Android’s <strong><em>UI</em></strong> thread context.</li><li>We invoke our function inside another coroutine created via <strong><em>async</em></strong>. The only difference is this coroutine returns a <strong><em>Deferred</em></strong> value. <strong><em>async</em></strong> is part of coroutine library.</li><li>We call <strong><em>await()</em></strong> function to capture future value of <strong><em>Deferred</em></strong> inside the second lambda parameter. This is captured inside <strong><em>UI</em></strong> context of the first coroutine.</li></ol><p>All in all, we have created an async executor where we can pass functions and have them execute asynchronously and then return values back to UI thread.</p><p>Now where can we use this -&gt; <strong>Room</strong> DB Queries :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f56435f99b38ba779c5d587c1419dd27/href">https://medium.com/media/f56435f99b38ba779c5d587c1419dd27/href</a></iframe><p>We can do an insert to DB with <strong><em>singleThreadAsync</em></strong> as an fire and forget request.</p><p>Whereas when we are retrieving data from DB, we can use our <strong><em>asyncExecutor </em></strong>to retrieve a list of objects and then apply all the kotlin goodness using operators from Collection Framework!</p><p>Hope you found this article useful!</p><p>You can reach me at twitter <a href="https://twitter.com/js_2892">here</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fe1f410570b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/demystifying-kotlin-coroutines-6fe1f410570b">Demystifying Kotlin Coroutines</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[Quick Tip: Network Profiler in Android Studio 3.1]]></title>
            <link>https://medium.com/android-news/quick-tip-network-profiler-in-android-studio-3-1-491e530ac8f2?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/491e530ac8f2</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 10:23:57 GMT</pubDate>
            <atom:updated>2018-03-29T10:23:57.627Z</atom:updated>
            <content:encoded><![CDATA[<p>Android Studio 3.1 recently came out of beta. It has a lot of features such as kotlin lint checks, D8 compiler and also a revamped <strong>Network Profiler</strong>.</p><p>From early days of DDMS, we could always check how network data was being consumed but the current iteration of profiler has added a whole new set of features. Let’s check them out</p><p>First of all, network graph looks pretty neat</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoKlMWet4KS8TXvHKE7jww.png" /></figure><h4>Request Debugging</h4><p>Clicking on any request in graph will give you it’s details such as Request type and Response data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1a470GtDWs6bLEXiMDvbdQ.png" /></figure><p>You can also check Request and Response headers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*yFFAIJYNDn1qSrHTQA8DNw.png" /><figcaption>Request headers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmaN_wczgEwG95M96wUE2g.png" /><figcaption>Response headers</figcaption></figure><p>If it’s a POST request, you can see body of request as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1bDXSRB1ZhnhRSpy3dVxQ.png" /><figcaption>POST Request</figcaption></figure><p>I have found this to be very <strong>useful</strong>. In past I have used tools such as <a href="https://www.charlesproxy.com/">Charles</a> to intercept and find request/response related details especially when dealing with third party APIs. This allows us to completely avoid that and check such details directly from Android Studio!</p><p>Bonus Point — If you are using third party SDKs, you can always check any arbitrary request going from your app and get details such as server url etc. Below is an example request sent from Crashlytics caught by the profiler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LRfcrGWNsulHPNnw_EIdA.png" /></figure><p>Always better know such things in advance, than <a href="https://medium.com/tow-center/the-graph-api-key-points-in-the-facebook-and-cambridge-analytica-debacle-b69fe692d747">getting red faced later.</a></p><h4>And one last thing</h4><p>Profiler can also help you catch radio bursts of high power when you’re on mobile network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfeXZeKxYAOz_tTF6qSfjw.png" /><figcaption>Radio’s mode shown in blue line</figcaption></figure><p>The graph presents a timeline of when your application causes the radio to remain in high power mode which in turn causes more battery consumption. You can use this to investigate network calls and make your application more battery friendly.</p><p>To understand more about Radio state machine, read <a href="https://developer.android.com/training/efficient-downloads/efficient-network-access.html#RadioStateMachine">here</a></p><p>That’s all. Thanks for reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491e530ac8f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/quick-tip-network-profiler-in-android-studio-3-1-491e530ac8f2">Quick Tip: Network Profiler in Android Studio 3.1</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Targeting Kotlin for both Android and iOS]]></title>
            <link>https://proandroiddev.com/targeting-kotlin-for-both-android-and-ios-dec5b967006a?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/dec5b967006a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[multiplatform]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Wed, 21 Mar 2018 08:36:01 GMT</pubDate>
            <atom:updated>2018-03-21T08:36:01.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8vwAg-xkjY6wHhtyyXgUA.png" /></figure><p>Kotlin has been traditionally used as a language for JVM based platforms and has become highly popular in Android ecosystem. As the language matures, it is knocking on new frontiers — platforms other than JVM, one of them being iOS.</p><p>Kotlin started out with compilation to .class files which allowed interoperability with Java and conversion to .dex for Android. But now with <a href="https://github.com/JetBrains/kotlin-native">Kotlin Native</a>, kotlin can target platforms which directly execute bytecode without a VM — emebedded systems, macOS and <strong>iOS.</strong></p><p>Let’s look at an example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91917c2e95e76430a13e3733914efddb/href">https://medium.com/media/91917c2e95e76430a13e3733914efddb/href</a></iframe><p>Above is a simple piece of code with multiple classes and variables written in kotlin. Important thing to note is that it is not importing any library except for <em>kotlin-stdlib</em></p><p>And here is a build.gradle for compiling this code into a jar</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ce57825918144e4c3d3643521b4c35c/href">https://medium.com/media/0ce57825918144e4c3d3643521b4c35c/href</a></iframe><p>Now we’ll compile this to a .jar using <em>./gradlew assemble</em> and then import this to an Android Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*GGGoF41MuTlrN4zoj_zUaQ.png" /><figcaption>Classes Generated</figcaption></figure><p>We can see three class files generated from Base.kt</p><ul><li>BaseKt.class — For constant API_KEY variable</li><li>Helper and Model both of which are seperate classes</li></ul><p>Now we can simple call this code in an Activity in a very straightforward way</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d4121316e26fb5e9fbc9201cad89ca6/href">https://medium.com/media/1d4121316e26fb5e9fbc9201cad89ca6/href</a></iframe><h3>Moving to iOS</h3><p>Let’s see if we can reproduce similar approach for iOS using Kotlin Native plugin.</p><p>In a folder above our Base project, we’ll add following build.gradle</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faf91e2d8780d7da96c51a95672f3b41/href">https://medium.com/media/faf91e2d8780d7da96c51a95672f3b41/href</a></iframe><p>Few things to note</p><ul><li><strong>konan</strong> is the plugin for Kotlin Native which allows targeting kotlin code to multiple platforms</li><li>konan.targets specify for which targets bytecode must be generated. We can also add other platform like <em>raspberry pi</em> to it.</li><li>konanArtifacts will specify artifacts to be generated along with their name and src directory if required.</li></ul><p>We will run <em>./gradlew build</em> on this which will produce the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nn6AHDhQU7Zvz9FBI4k4sg.png" /><figcaption>Objective C framework created after build</figcaption></figure><p>We now have a file named <strong>Base.framework</strong> which is an <strong>iOS framework</strong> file and can be directly imported to Xcode. Let’s do that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*yqpst-IZIxBYesSVAm57IA.png" /><figcaption>Link framework file to a project</figcaption></figure><p>We have received something called<strong> Base.h </strong>from the framework which contains code converted from <strong>Base.kt</strong> .</p><p>Header files are a little complex to read but Xcode provides Swift conversion of such files for better understanding. Here is an excerpt of what is present in header file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74bc7a29dd5dd1016a0026346449f83/href">https://medium.com/media/b74bc7a29dd5dd1016a0026346449f83/href</a></iframe><ul><li>By default a class named <strong>KotlinBase </strong>is created which extends NSObject and also implements NSCopying and all other classes extend this class.</li><li>All classes have prefix “Base” which is the name we provided in build.gradle while creating the iOS framework</li><li><strong>Int</strong> from Kotlin is converted to <strong>Int32</strong> in Swift not <em>Int(Swift).</em></li><li>Kotlin’s List&lt;T&gt; is converted to a Swift Array.</li><li>Companion object is converted to a separate class with an init() method.</li><li>Module level constant API_KEY is converted to an function within a class.</li><li><strong>BaseModel </strong>which is derived from a data class has a function <em>doCopy </em>similar to copy() of data class. But default initialization or copy is not possible as all arguments must be specified while initializing or copying.</li></ul><p>Now let’s try to call these functions from a Swift file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21199600e361452a0af45fe02ff9e7ed/href">https://medium.com/media/21199600e361452a0af45fe02ff9e7ed/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*MdYOXbj0Mpias_biYP2xDw.gif" /></figure><p>So we took a piece of raw Kotlin code and ran it on multiple platforms without actually changing anything on the platform side code. Although above code may not be useful for production level applications, but in future as Kotlin Native and Kotlin Mutliplatform gets mature, we should be able to move more logic towards a common project.</p><p><a href="https://github.com/Kotlin/kotlinx.serialization">Kotlinx Serialization</a> is a library built on this concept and supports JVM/JS for now with native support coming soon. With this we should be able to serialize/deserialize data classes to JSON on all platforms with single lib.</p><p>Full code here</p><p><a href="https://github.com/jitinsharma/kotlin_multi_target">jitinsharma/kotlin_multi_target</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dec5b967006a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/targeting-kotlin-for-both-android-and-ios-dec5b967006a">Targeting Kotlin for both Android and iOS</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[Kotlin Serialization Library]]></title>
            <link>https://medium.com/android-news/kotlin-serialization-library-38bf85d8768b?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/38bf85d8768b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[serialization]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Thu, 25 Jan 2018 15:55:30 GMT</pubDate>
            <atom:updated>2018-01-25T15:55:30.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*20QWLBqDNs5YSN_0jD8FfA.png" /></figure><p>Kotlin has recently released a library for serialization. To put things in perspective, before this there was no serialization lib provided by kotlin but you could use any platform supported serialization libraries with Kotlin classes(eg. Gson for JVM/Android)</p><p>But that’s where Kotlin’s serialization library is different, it’s cross platform and supports multiple formats. The whole lib is built on top of Kotlin’s multiplatform concept.</p><p>Currently kotlinx.serialization supports three formats</p><ul><li>JSON</li><li>CBOR</li><li>Protobuf</li></ul><p>And platforms are JVM and JS, but others should get added soon as Kotlin/native becomes mature.</p><p>Let’s take a look at JSON</p><p>Marking @Serializable will make a class serializable.</p><pre>@Serializable<br>data class Destination(<br>        var name : String? = &quot;&quot;,<br>        var country : String? = &quot;&quot;,<br>        var code : Int = 0,<br>)</pre><p>stringify will convert a serializable object to JSON string.</p><pre>val delhi = Destination(name = &quot;Delhi&quot;, country = &quot;India&quot;, code = 0)<br>val delhiAsString = JSON.<strong>stringify</strong>(delhi)<br><em>println</em>(delhiAsString)<br>// {&quot;name&quot;:&quot;Delhi&quot;,&quot;country&quot;:&quot;India&quot;,&quot;code&quot;:0}</pre><p>parse will convert well formed json back to a data class.</p><pre>val newYork = JSON.<strong>parse</strong>&lt;Destination&gt;(<br>        &quot;{\&quot;name\&quot;:\&quot;New York\&quot;,\&quot;country\&quot;:\&quot;USA\&quot;,\&quot;code\&quot;:3}&quot;<br>)<br><em>println</em>(newYork)<br>// Destination(name=New York, country=USA, code=3)</pre><p>Parsing has multiple options like</p><pre>val paris = JSON<strong>.unquoted.parse</strong>&lt;Destination&gt;(<br>        &quot;{name:Paris,country:France,code:10}&quot;)<br><em>println</em>(paris)<br>// Destination(name=Paris, country=France, code=10)</pre><p>In above example, json string doesn’t have quotes. We can parse such json with JSON.unquoted. This can be helpful during debugging.</p><p>Here’s a definition of all such properties available</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVs5EHVIHD7OkRImEhkucA.png" /></figure><h4><strong>Additional Properties</strong></h4><p>Often our data objects have properties which could be optional. For example, there could be extra properties which we initialize on client side which server may not provide while fetching the json. Similarly there may be properties which may or may not be present in json. Fortunately the lib handles both cases.</p><pre><strong>@Optional</strong><br>var isMetro : Boolean = false,<br><strong>@Transient</strong><br>var favorite : Boolean = false</pre><p>Optional — This value will considered during serialization/deserialization. but if not present, it won’t break serialization.</p><p>Transient — This value will not be considered during serialization/deserialization. But if present in json, it will cause an exception.</p><pre>var barcelona = JSON.unquoted.parse&lt;Destination&gt;(<br>        &quot;{name:Barcelona,country:Spain,code:5}&quot;)<br><em>println</em>(barcelona)<br>// Only optional and transient missing, so serialization works<br>// Destination(name=Paris, country=France, code=10, isMetro=false, favorite=false)<br><br>barcelona = JSON.unquoted.parse(<br>        &quot;{name:Barcelona,country:Spain,code:5,<strong>isMetro:true</strong>}&quot;)<br><em>println</em>(barcelona)<br>// Destination(name=Barcelona, country=Spain, code=5, <strong>isMetro=true</strong>, favorite=false)<br>// Optional property isMetro is updated but Transient property favorite remains same<br><br>barcelona = JSON.unquoted.parse(<br>        &quot;{name:Barcelona,code:5,isMetro=true}&quot;)<br>// This will break as &quot;<strong>country</strong>&quot; is a required field.</pre><pre>barcelona = JSON.unquoted.parse(<br>        &quot;{name:Barcelona,country:Spaincode:5,<br>isMetro=true,<strong>favorite=true</strong>}&quot;)<br>// This will break as &quot;<strong>favorite</strong>&quot; is not recognised by serializer</pre><blockquote>If you’re not sure about consistency of values in json, using JSON.nonstrict might be a good idea to avoid exceptions</blockquote><h4>Class variables can have different names than the name of key in json. Just annotate using @SerialName</h4><pre>@SerialName(&quot;d_country&quot;)<br>var country : String = &quot;&quot;</pre><h3>Additional Utilities</h3><p>There are few utilities also available out of box</p><p><strong>Mapper</strong></p><p>Mapper can convert a object to a map — straightforward.</p><pre>val newYorkAsMap : Map&lt;String,Any&gt; = Mapper.map(newYork) // Mapping<br>val newNewYork = Mapper.unmap&lt;Destination&gt;(newYorkAsMap) //UnMapping<br>// Use Mapper.mapNullable() to support null values</pre><p><strong>ValueTransformer</strong></p><p>Transformer allows custom transformation on each value of object.</p><pre>object CustomTransformer : ValueTransformer() {<br><br>    override fun transformStringValue(desc: KSerialClassDesc, index: Int, value: String): String =<br>            value.<em>toLowerCase</em>()<br><br>    override fun transformIntValue(desc: KSerialClassDesc, index: Int, value: Int): Int =<br>            when(value) {<br>                0 -&gt; 1<br>                else -&gt; super.transformIntValue(desc, index, value)<br>            }<br>}</pre><pre>val newDelhi = CustomTransformer.transform(delhi)<br><em>println</em>(newDelhi)<br>// Destination(name=delhi, country=india, code=1)<br>// Strings are lowercase and integer code 0 became 1</pre><p>There are more override methods for float, boolean etc in ValueTransform.</p><p><strong>Custom Serialization</strong></p><p>The lib allows you to define your own serialization scheme if required.</p><pre>@Serializable<br>data class Country(var name : String = &quot;&quot;, var hCode : Int = -1) {<br><br>    @Serializer(forClass = Country::class)<br>    companion object : KSerializer&lt;Country&gt;{<br><br>        override fun load(input: KInput): Country {<br>            <em>TODO</em>(&quot;Write your own scheme to handle input&quot;)<br>        }<br><br>        override fun save(output: KOutput, obj: Country) {<br>            <em>TODO</em>(&quot;Write your own scheme to handle output&quot;)<br>        }<br><br>        override val serialClassDesc: KSerialClassDesc<br>            get() = <em>TODO</em>()<br>    }<br>}</pre><p>Full doc here</p><p><a href="https://github.com/Kotlin/kotlinx.serialization">GitHub - Kotlin/kotlinx.serialization: Kotlin multiplatform / multi-format serialization</a></p><p>Code gist: <a href="https://gist.github.com/jitinsharma/8805cf63ba3b371b657531d55d3fd6c5">https://gist.github.com/jitinsharma/8805cf63ba3b371b657531d55d3fd6c5</a></p><p>Thanks for reading!</p><p>Please provide your thoughts in comments and don’t forget to clap if you liked the story.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38bf85d8768b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/kotlin-serialization-library-38bf85d8768b">Kotlin Serialization Library</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with Kotlin Higher Order Functions]]></title>
            <link>https://medium.com/android-news/playing-with-kotlin-higher-order-functions-aecce3d72a12?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/aecce3d72a12</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Thu, 07 Dec 2017 10:16:50 GMT</pubDate>
            <atom:updated>2017-12-17T19:10:04.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Kzt7N2Cs3MtmoB1W3BqMYg.jpeg" /></figure><p>One of the cool things in Kotlin is having ability to pass around functions as objects. That’s where higher order functions come and allow us to write code more declaratively.</p><p>I’m gonna list down some function blocks</p><p>Let’s start with basic ones</p><p>We often run into scenarios where we encapsulate logic inside try/catch block but just log the exception in catch block. Sometimes even the catch seems useless, <em>so…</em></p><pre>inline fun &lt;T&gt; justTry(block: () -&gt; T) = try { block() } catch (e: Throwable) {}</pre><p>And now we just forget the catch block</p><pre><em>justTry </em><strong>{<br>    </strong>myFunctionWhichMayFail()<br><strong>}</strong></pre><p>Similarly</p><pre>inline fun debugMode(block : () -&gt; Unit) {<br>    if (BuildConfig.<em>DEBUG</em>) {<br>        block()<br>    }<br>}</pre><pre>inline fun lollipopAndAbove(block : () -&gt; Unit) {<br>    if (Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>LOLLIPOP</em>) {<br>        block()<br>    }<br>}</pre><pre>inline fun Context.withNetwork(block: () -&gt; Unit) {<br>    val connectivityManager = this<br>            .getSystemService(Context.<em>CONNECTIVITY_SERVICE</em>) as? ConnectivityManager<br>    connectivityManager?.<em>let </em><strong>{<br>        </strong>val netInfo = <strong>it</strong>.<em>activeNetworkInfo<br>        </em>netInfo?.<em>let </em><strong>{<br>            </strong>if (netInfo.<em>isConnected</em>) {<br>                block()<br>            }<br>        <strong>}<br>    }<br></strong>}</pre><p>transforms to</p><pre><em>debugMode </em><strong>{<br>    </strong>StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder()<br>            .detectAll()<br>            .penaltyLog()<br>            .build())<br><strong>}<br><br></strong><em>lollipopAndAbove </em><strong>{<br>    </strong>view.<em>elevation </em>= 1.0f<br><strong>}</strong></pre><pre><em>withNetwork </em><strong>{<br>    </strong>// make network request<br><strong>}</strong></pre><p>Again, this makes code more readable and looks nice :)</p><p><strong>Note</strong>: <em>lollipopAndAbove </em>closure gives minSdk error in AS 3.0. Maybe a lint related error.</p><blockquote>But one should consider the logic which should be transformed into function block. The above code block only has if condition which works fine but if there needs to be an else section, we may wanna avoid function blocks. This is valid for withConnection {} where an else case may be required to show some message for network connectivity.</blockquote><p>Moving on to more cool stuff</p><pre>fun &lt;T&gt; asyncRxExecutor(heavyFunction: () -&gt; T, response : (response : T?) -&gt; Unit) {<br>    val observable = Single.create&lt;T&gt;(<strong>{</strong>e <strong>-&gt;<br>        </strong>e.onSuccess(heavyFunction())<br>    <strong>}</strong>)<br>    observable.subscribeOn(Schedulers.newThread())<br>            .observeOn(AndroidSchedulers.mainThread())<br>            .subscribe <strong>{ </strong>t: T? <strong>-&gt;<br>                </strong>response(t)<br>            <strong>}<br></strong>}</pre><p>The above code is a generic function which accepts a function as a first parameter, executes using RxJava observable in a new thread and then sends back response exposed as a lambda. Here is a sample usage</p><pre><em>asyncRxExecutor</em>(<strong>{ </strong>myHeavyFunction() <strong>}</strong>, <strong>{ </strong>response <strong>-&gt;<br>    </strong><em>println</em>(response.<em>toString</em>())<br><strong>}</strong>)</pre><p>So basically we took an arbitrary function which was already written or may be written in future , did it’s execution asynchronously and returned a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*A2gir0uUVzdlgiEkPUoyvQ.png" /></figure><p>We could use different mechanism for async execution like Kotlin Coroutines</p><pre>fun &lt;T&gt; asyncCoroutinesExecutor(heavyFunction: () -&gt; T, response : (response : T?) -&gt; Unit) {<br>    <em>async</em>(<em>UI</em>) <strong>{<br>        </strong>val data : Deferred&lt;T&gt; = <em>bg </em><strong>{<br>            </strong>heavyFunction()<br>        <strong>}<br>        </strong>response(data.await())<br>    <strong>}<br></strong>}</pre><pre><em>asyncCoroutinesExecutor</em>(<strong>{ </strong>myHeavyFunction() <strong>}</strong>, <strong>{ </strong>response <strong>-&gt;<br>    </strong><em>println</em>(response.<em>toString</em>())<br><strong>}</strong>)</pre><p>We can similarly create an executor for running code on ui thread.</p><pre>inline fun uiThreadExecutor(crossinline block: () -&gt; Unit) {<br>    val mainHandler = Handler(Looper.getMainLooper())<br>    mainHandler.post<strong>{<br>        </strong>block()<br>    <strong>}<br></strong>}</pre><p>and…</p><pre><em>thread </em><strong>{<br>    </strong>myHeavyFunction()<br>    <em>uiThreadExecutor </em><strong>{<br>        </strong>view.<em>text </em>= &quot;Just updating&quot;<br>    <strong>}<br>    </strong>myAnotherHeavyFunction()<br><strong>}</strong></pre><blockquote>thread {} is provided by Kotlin itself for running code in a thread.</blockquote><p>This is just the tip of the iceberg of what we can do with higher order functions!</p><p>I’m maintaining a repo where I add utilities like this. Have a look</p><p><a href="https://github.com/jitinsharma/Kotlin.someExtensions">jitinsharma/Kotlin.someExtensions</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aecce3d72a12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/playing-with-kotlin-higher-order-functions-aecce3d72a12">Playing with Kotlin Higher Order Functions</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using FrameMetrics to track UI performance - Part 1]]></title>
            <link>https://jitin-sharma.medium.com/using-framemetrics-to-track-ui-performance-part-1-9c5d514a239d?source=rss-d5b7562e9257------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5d514a239d</guid>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Jitin Sharma]]></dc:creator>
            <pubDate>Sun, 13 Nov 2016 13:41:00 GMT</pubDate>
            <atom:updated>2016-11-13T13:41:00.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Android Nougat(7.0) introduced a nice feature to get UI performance data at runtime using <a href="https://developer.android.com/reference/android/view/FrameMetrics.html">FrameMetrics</a>. Now this is not a new feature as same can be done using <em>adb shell dumpsys gfxinfo.</em></p><p>FrameMetrics can be useful if you want to track UI performance data in production apps where your environment is expanded over to possibly billion devices, with different OS,RAM,processor etc and one factor unique to each device: <strong>The User.</strong></p><p>Let’s get on to code.</p><p>Initialize a FrameMetrics Listener with handler. A handler is required because you want to listen to events after animations and layout rendering is complete.</p><pre>FrameMetrics metrics;</pre><pre>Handler handler = new Handler();<br>getWindow().addOnFrameMetricsAvailableListener(new Window.OnFrameMetricsAvailableListener() {<br>    @Override<br>    public void onFrameMetricsAvailable(Window window, FrameMetrics frameMetrics, int i) {<br>        metrics = new FrameMetrics(frameMetrics);<br>    }<br>}, handler);</pre><p>Get metrics after a certain delay(customize for yourself)</p><pre>handler.postDelayed(new Runnable() {<br>    @Override<br>    public void run() {<br><br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;ANIMATION_DURATION: &quot; + metrics.getMetric((<strong>FrameMetrics.<em>ANIMATION_DURATION</em></strong>)) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;COMMAND_ISSUE_DURATION: &quot; + metrics.getMetric(FrameMetrics.<em>COMMAND_ISSUE_DURATION</em>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;DRAW_DURATION: &quot; + metrics.getMetric(<strong>FrameMetrics.<em>DRAW_DURATION</em></strong>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;FIRST_DRAW_FRAME: &quot; + metrics.getMetric(FrameMetrics.<em>FIRST_DRAW_FRAME</em>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;INPUT_HANDLING_DURATION: &quot; + metrics.getMetric(FrameMetrics.<em>INPUT_HANDLING_DURATION</em>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;LAYOUT_MEASURE_DURATION: &quot; + metrics.getMetric(<strong>FrameMetrics.<em>LAYOUT_MEASURE_DURATION</em></strong>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;SWAP_BUFFERS_DURATION: &quot; + metrics.getMetric(FrameMetrics.<em>SWAP_BUFFERS_DURATION</em>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;SYNC_DURATION: &quot; + metrics.getMetric(FrameMetrics.<em>SYNC_DURATION</em>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;TOTAL_DURATION: &quot; + metrics.getMetric(<strong>FrameMetrics.<em>TOTAL_DURATION</em></strong>) / Math.<em>pow</em>(10, 6));<br>        Log.<em>d</em>(&quot;Metrics&quot;, &quot;UNKNOWN_DELAY_DURATION: &quot; + metrics.getMetric(FrameMetrics.<em>UNKNOWN_DELAY_DURATION</em>) / Math.<em>pow</em>(10, 6));<br><br>    }<br>}, 2000);</pre><blockquote>FrameMetrics Listener can be used multiple times within your application to listen for animation durations as well as track layout measuring time for dynamic views.</blockquote><p>Here is a sample output(in seconds) with an empty Relative layout running on Nexus 5 emulator with API 24. <em>Complex definitions </em><a href="https://developer.android.com/reference/android/view/FrameMetrics.html#ANIMATION_DURATION"><em>here</em></a></p><pre>ANIMATION_DURATION: 0.03<br>COMMAND_ISSUE_DURATION: 34.288<br>DRAW_DURATION: 0.401<br>FIRST_DRAW_FRAME: 0.0<br>INPUT_HANDLING_DURATION: 0.045<br>LAYOUT_MEASURE_DURATION: 0.425<br>SWAP_BUFFERS_DURATION: 5.861<br>SYNC_DURATION: 0.04<br>TOTAL_DURATION: 47.534289<br>UNKNOWN_DELAY_DURATION: 5.159289</pre><p>In part 2, we’ll try to analyze what these values mean and how to best analyze data provided by FrameMetrics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5d514a239d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>