<?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 Sarabjeet Singh on Medium]]></title>
        <description><![CDATA[Stories by Sarabjeet Singh on Medium]]></description>
        <link>https://medium.com/@sabbispeak?source=rss-e28fb631a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YsE4quhDDTh1vRvSM-XWYg.png</url>
            <title>Stories by Sarabjeet Singh on Medium</title>
            <link>https://medium.com/@sabbispeak?source=rss-e28fb631a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:42:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sabbispeak/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[Exploring Dynamic Feature Modules at Swiggy]]></title>
            <link>https://medium.com/swiggy-bytes/exploring-dynamic-feature-modules-at-swiggy-83019ebfa980?source=rss-e28fb631a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/83019ebfa980</guid>
            <category><![CDATA[swiggy-mobile]]></category>
            <category><![CDATA[dynamic-feature-module]]></category>
            <category><![CDATA[swiggy-engineering]]></category>
            <category><![CDATA[swiggy]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sarabjeet Singh]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 15:02:17 GMT</pubDate>
            <atom:updated>2020-01-22T09:17:09.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1QNXNpRgjdaU3t5oSsKOg.png" /><figcaption><a href="https://undraw.co/">https://undraw.co/</a></figcaption></figure><p>This blog is a part of our App Size Reduction <a href="https://bytes.swiggy.com/swiggy-app-on-diet-a364fec20081"><strong>Blog Series</strong></a> at Swiggy, we will be discussing Google Play’s<strong><em> </em></strong><a href="https://developer.android.com/studio/projects/dynamic-delivery"><strong>Dynamic Delivery</strong></a><em> </em>which is one of the <a href="https://developer.android.com/guide/app-bundle/"><strong>App Bundle</strong></a><strong> </strong>features<strong> </strong>released<strong> </strong>to help developers to reduce app size and streamline the release process. We will be talking about the requirements and basic implementation of Dynamic Feature modules (DFM)<strong> </strong>along with how we shipped <a href="https://play.google.com/store/apps/details?id=in.swiggy.android.daily&amp;hl=en_IN"><strong>Swiggy Daily’s</strong></a> Helpcenter as a dynamic feature module, the problems we encountered and the solutions we came up with.</p><h3>What is Dynamic Delivery?</h3><p>Dynamic delivery allows you to download the modules <strong>on-demand</strong> in order to optimize the app install size from the play store. Users can later download and install the components on-demand after they’ve already installed the base APK of the app.</p><p>For example, consider a text messaging app with functionality that allows you to capture and send picture messages. But we know that only a small percentage of users send picture messages. It may make sense to include picture messaging as a downloadable dynamic feature module. That way, the initial app download is smaller for all users and only those users who send picture messages need to download that additional component.</p><h4>Prerequisites Before you start</h4><ul><li><strong>Modular CodeBase:</strong> Keep in mind that in order to use on-demand delivery one needs a modularized code base and this type of modularization requires more effort and possibly refactoring the app’s existing code. So carefully consider which of your app’s features would benefit the most from being available to users on-demand. At Swiggy we have divided our codebase into independent and interchangeable modules which give us advantages on build time improvement, better reusability across other apps and fine-grained dependency control.</li><li><strong>Deciding on Feature: </strong>Deciding which feature to ship on Demand should be considered properly, you don’t want to ship a feature that provides the main functionality for your app since the user has to wait for the module to get downloaded before they can use the app. This will result in a drop in user conversion numbers. At Swiggy, we decided to ship our Help and Support Section as an on-demand module because only a small number of users use this feature that too in cases of any grievance. <em>In the future, we are planning to ship OnBoarding as a dynamic module since we can uninstall the modules that are not needed. This helps us in further optimizing the app size on the user device.</em></li></ul><p>Now that we have some basic understanding of what dynamic delivery is and how it changes the dependencies for our project, we are ready for some hands-on code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*6sSWdWI_CTEydy0T7Pyxjg.gif" /><figcaption>let&#39;s dive in</figcaption></figure><h3>Creating a dynamic feature module</h3><p>You can either create a new dynamic module from Android Studio File options or convert an exciting module or library into a dynamic feature module.</p><h4><strong>Creating a new dynamic feature module</strong></h4><p>This a strait-forward step where android studio generates all the required files for your dynamic feature module, follow these steps</p><ol><li>Select <strong>File &gt; New &gt; New Module</strong> from the menu bar. In the Create <strong>New Module</strong> dialog, select <strong>Dynamic Feature Module </strong>and click<strong> Next</strong>.</li><li>On the <strong>Configure your new module</strong> screen, give your <strong>module</strong> a name</li><li>On the <strong>Module Download </strong>screen, specify the <strong>module title</strong></li><li>Hit <strong>Finish</strong> and wait for the project to sync. And we got ourself our first dynamic feature module :)</li></ol><h4><strong>Converting a module/lib into a DFM</strong></h4><p>We need to do some work to convert an existing module to the dynamic feature module, follow the below steps.</p><p><strong>1. Changes in module <em>build.gradle</em> file</strong></p><pre>// Replace this plugin in your module/lib gradle file<br>apply plugin: &#39;com.android.library&#39;</pre><pre>// with this plugin<br><strong>apply plugin: &#39;com.android.dynamic-feature&#39;<br></strong>apply plugin: &#39;kotlin-android&#39;<br>apply plugin: &#39;kotlin-kapt&#39;</pre><pre>android {<br>    dataBinding {<br>        enabled = true<br>    }<br>}</pre><pre>dependencies {<br>    implementation fileTree(dir: &#39;libs&#39;, include: [&#39;*.jar&#39;])<br>    implementation project(&#39;:app&#39;)<br>}</pre><ul><li><strong>com.android.dynamic-feature</strong> the plugin includes the Gradle tasks and properties required to configure and build an app bundle that includes your dynamic feature module.</li><li>If you are using <a href="https://developer.android.com/topic/libraries/data-binding"><strong><em>Data Binding</em></strong></a> in your module don’t forget to enable it and add this proguard rule to keep the BindingMapper class for our feature module in our case helpmodule</li></ul><pre><strong>-keep class in.swiggy.android.helpmodule.DataBinderMapperImpl { *; }</strong></pre><ul><li><strong>What not to include:</strong><br> — <strong>Signing configurations: </strong>App bundles are signed using signing configurations of the base module.<br> — <strong>The </strong><strong>minifyEnabled property: </strong>You can <a href="https://developer.android.com/studio/build/shrink-code#shrink-code"><strong><em>enable code shrinking</em></strong></a> for your entire app project from only the base module’s build configuration.<br>— <strong>versionCode and </strong><strong>versionName</strong>: Gradle uses app version information that the base module provides.</li></ul><p><strong>2. Changes in module AndroidManifest.xml</strong></p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:dist=&quot;http://schemas.android.com/apk/distribution&quot;<br>    package=&quot;in.swiggy.android.helpmodule&quot;&gt;</pre><pre>    &lt;dist:module<br>        dist:instant=&quot;false&quot;<br>        dist:onDemand=&quot;true&quot;<br>        dist:title=&quot;@string/title_helpdfm&quot;&gt;<br>        &lt;dist:fusing dist:include=&quot;true&quot; /&gt;<br>    &lt;/dist:module&gt;</pre><pre>&lt;application&gt;</pre><pre>    &lt;activity ............<br>       <br>&lt;/application&gt;</pre><pre><br>&lt;/manifest&gt;</pre><ul><li><strong>&lt;dist:module </strong>This new XML element defines attributes that determine how the module is packaged and distributed as APKs.</li><li><strong>dist:instant=&quot;true | false&quot;</strong>Specifies whether the module should be available through <a href="https://developer.android.com/topic/google-play-instant/overview">Google Play Instant</a> as an instant experience.</li><li><strong>dist:onDemand=&quot;true | false&quot;</strong>Specifies that the module should be available as an on demand download.</li><li><strong>dist:title=&quot;@string/feature_name&quot;</strong>Specifies a user-facing title for the module <strong><em>You need to include the string resource for this title in the base module’s strings.xml file</em></strong></li><li><strong>&lt;dist:fusing dist:include=&quot;true | false&quot; /&gt; </strong>Specifies whether to include the module in multi-APKs that target devices running Android 4.4 (API level 20) and lower.</li></ul><p><strong>3. Changes in Base module build.gradle</strong></p><pre>apply plugin: &#39;com.android.application&#39;<br>apply plugin: &#39;kotlin-android&#39;<br>apply plugin: &#39;kotlin-kapt&#39;<br><br>android {<br><br> .......</pre><pre>buildTypes {<br><br>        release {<br>            zipAlignEnabled true<br>            minifyEnabled true<br><strong>            shrinkResources false<br></strong>            debuggable false<br>            useProguard true<br>        }<br>    }<br>.......</pre><pre>// add name of the module here<br><strong>    dynamicFeatures = [&quot;:helpmodule&quot;]<br> <br> .......</strong></pre><pre>}</pre><ul><li>Add Dynamic feature module dependencies to the base module using <strong>dynamicFeatures</strong> properties in build.gradle</li><li>We cannot use <strong>shrinkResources</strong> if we have dynamic feature modules present, since enabling it removes the dynamic feature from the apk. There is an <a href="https://issuetracker.google.com/issues/120517460"><strong>ongoing discussion</strong></a> on whether will it be enabled in future</li></ul><h3>Dependency Injection Graph</h3><p>With <a href="https://developer.android.com/studio/projects/dynamic-delivery#customize_delivery">dynamic feature modules</a>, the way modules usually depend on each other is inverted. Instead of the app module the dynamic feature modules depend on the app module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75yNdqfZ5fdRvW3jstHhdw.png" /><figcaption>Example of a Dagger graph in a project with dynamic feature modules</figcaption></figure><p>In Dagger, components need to know about their subcomponents. This information is included in a Dagger module added to the parent component (like the SubcomponentsModule module in <a href="https://developer.android.com/training/dependency-injection/dagger-android#dagger-subcomponents">Using Dagger in Android apps</a>). Unfortunately, with the reversed dependency between the app and the dynamic feature module, the subcomponent is not visible from the app module because it&#39;s not in the build path.</p><p>Dagger has a mechanism called <strong>component dependencies</strong> that you can use to solve this issue. Instead of the child component being a subcomponent of the parent component, the child component is dependent on the parent component. With that, there is no parent-child relationship; now <strong>components</strong> depend on others to get certain <strong>dependencies</strong>. As an example, a LoginComponent defined in a login dynamic feature module depends on AppComponent defined in app module to provide the dependencies</p><pre>@Component(dependencies = [AppComponent::class])<br>interface LoginComponent {<br>    fun inject(activity: LoginActivity)<br>}</pre><blockquote><em>A DFM can access Dagger components from the application module. The application module can access components from libraries it depends on. But not the other way around.</em></blockquote><p>But at Swiggy, we had one more challenge which we needed to solve before we go on to build our dependency graph. Our feature modules are not dependent on the app module either. So we can’t depend on the common component. We came up with a different approach to pass Dependencies to our feature modules i.e. using <strong><em>Component Builder Pattern</em></strong></p><pre>@FragmentScope<br>@Component(modules = [AndroidSupportInjectionModule::class])<br>interface HelpCenterComponent {</pre><pre>    fun inject(helpCenterFragment: HelpCenterFragment)</pre><pre>    @Component.Builder<br>    interface Builder{</pre><pre>        fun build(): HelpCenterComponent</pre><pre>        @BindsInstance<br>        fun provideSharedPref(pref: SharedPreferences): Builder</pre><pre>        @BindsInstance<br>        fun provideGson(gson: Gson): Builder</pre><pre>    }<br>}</pre><p>As shown above our HelpCenterFragement need SharedPreferences and Gson objects as a dependency to work. Hence, we created a common Interface named IHelpDependencyProvider which would be a part of a common module on which both the app and our dynamic feature module depends</p><pre>interface IHelpDependencyProvider {</pre><pre>    fun provideSharedPreference(): SharedPreferences</pre><pre>    fun provideGson(): Gson</pre><pre>}</pre><p>Our <strong><em>Application</em></strong> class will extend this interface and provide the dependencies which we can request in our Fragments <strong><em>onAttach</em></strong> method and casting the <strong><em>applicationcontext</em></strong> to above interface</p><pre>override fun onAttach(context: Context) {<br>    super&lt;androidx.fragment.app.Fragment&gt;.onAttach(context)<br>    SplitCompat.install(context)<br>    val provider = (context.applicationContext as IHelpDependencyProvider)<br>    DaggerHelpCenterComponent.builder()<br>        .provideSharedPref(provider.provideSharedPreference())<br>        .provideGson(provider.provideGson())<br>        .build()<br>        .inject(this)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*o47ioWJ7q3uW1SHB5IcAJQ.gif" /><figcaption>Downloading HelpCentre on Demand Module in <a href="https://play.google.com/store/apps/details?id=in.swiggy.android.daily&amp;hl=en_IN"><strong>Swiggy Daily</strong></a></figcaption></figure><h3>Downloading dynamic feature modules</h3><p>With Google Play’s Dynamic Delivery, the app can download dynamic feature modules on demand to devices running Android 5.0 (API level 21) and higher. You can also use this API to download on-demand modules for your Android Instant Apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CaTbx4qb236Jltr8rNT4w.png" /><figcaption>Showing the downloading state when the module is downloading in <a href="https://play.google.com/store/apps/details?id=in.swiggy.android.daily&amp;hl=en_IN"><strong>Swiggy Daily</strong></a> App</figcaption></figure><h4>Include the Play Core Library in your app’s build.gradle</h4><pre>dependencies {<br>    implementation &#39;com.google.android.play:core:1.6.4&#39;<br>}</pre><p><em>Note: Do not forget to add </em><a href="https://developer.android.com/studio/build/dependencies.html#google-maven"><em>Google’s Maven Repository</em></a><em> in project’s build.gradle.</em></p><h4>Request an on-demand dynamic feature module</h4><p>There are two ways to request an on-demand module:</p><ul><li><strong>Using </strong><a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/SplitInstallManager#startinstall"><strong>SplitInstallManager.startInstall()</strong></a>: Your app needs to be in the foreground to submit the request. When your app requests an on-demand module, the Play Core Library employs a “fire-and-forget” strategy in an async fashion. That is, it sends the request to download the module to the platform, but it does not monitor whether the installation succeeded. So you are responsible for monitoring the request state (explained later).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9efc11854fd4cadb302cc18e1c2f3678/href">https://medium.com/media/9efc11854fd4cadb302cc18e1c2f3678/href</a></iframe><blockquote><strong><em>Note:</em></strong><em> To have immediate access to the module’s code and resources, your app needs to </em><a href="https://developer.android.com/guide/app-bundle/playcore#access_downloaded_modules"><em>enable SplitCompat</em></a><em>.</em></blockquote><ul><li><strong>Using </strong><a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/SplitInstallManager#deferredinstall"><strong>SplitInstallManager.deferredInstall()</strong></a>: If you want to defer installation for when the app is running in the background. Request for deferred install is best-effort and you cannot track its progress. So, before trying to access a module you have specified for deferred installation, you should check whether the module has been installed or not (explained later).</li></ul><pre>splitInstallManager.deferredInstall(Arrays.asList(&quot;dynamicModule&quot;));</pre><blockquote><strong>Note:</strong> It’s okay to request a dynamic feature module that’s already installed on the device. The API instantly considers the request as completed if it detects the module is already installed.</blockquote><blockquote>Additionally, after a module is installed, Google Play keeps it updated automatically. That is, when you upload a new version of your app bundle, the platform updates all installed APKs that belong to your app</blockquote><h4>Monitor the Request State of an on-demand module</h4><p>To be able to update a progress bar, fire an intent after installation, or gracefully handle a request error, you need to listen for state updates from the asynchronous SplitInstallManager.startInstall() task. Before you can start receiving updates for your install request, register a listener and get the session ID for the request, as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3915f5d61ec14afe312a47eadb36e18/href">https://medium.com/media/c3915f5d61ec14afe312a47eadb36e18/href</a></iframe><p>Check the available <a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/model/SplitInstallErrorCode"><strong><em>SplitInstallErrorCode</em></strong></a> and <a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/model/SplitInstallSessionStatus.html"><strong><em>SplitInstallSessionStatus</em></strong></a> to gracefully handle the state change and errors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8mhP0Z8028cSfzVzHeXWw.png" /><figcaption>Handling the error states for module install in <a href="https://play.google.com/store/apps/details?id=in.swiggy.android.daily&amp;hl=en_IN"><strong>Swiggy Daily</strong></a> App</figcaption></figure><h3>Managing dynamic feature modules</h3><ul><li>To cancel a request before it is installed, you can do so by invoking the <a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/SplitInstallManager#cancelinstall">cancelInstall()</a> method using the request’s session ID.</li></ul><pre>splitInstallManager.cancelInstall(mySessionId);</pre><ul><li>To check currently installed dynamic feature modules on the device, you can call<a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/SplitInstallManager.html#getInstalledModules()">SplitInstallManager.getInstalledModules()</a>.</li></ul><pre>Set&lt;String&gt; installedModules = splitInstallManager.getInstalledModules();</pre><ul><li>To uninstall modules, invoke <a href="https://developer.android.com/reference/com/google/android/play/core/splitinstall/SplitInstallManager.html#deferreduninstall">deferredUninstall(List&lt;String&gt; modules)</a></li></ul><pre>splitInstallManager.deferredUninstall(Arrays.asList(&quot;moduleName&quot;));</pre><h3>How Swiggy Daily uses on Demand Modules</h3><p>We have successfully shipped the HelpCentre and Support Section as a dynamic feature module in the <a href="https://play.google.com/store/apps/details?id=in.swiggy.android.daily&amp;hl=en_IN"><strong><em>Swiggy Daily App</em></strong></a><strong><em>.</em></strong> We saw an <strong><em>app size reduction of 100kb</em></strong> in our base APK. We have different flows from where we fire install request for HelpCentre on-demand module.</p><ul><li><strong>Account Section</strong>: When the users navigate to Account Section of Daily App we trigger an install request for dynamic feature module, see the below image to see how we handle the intermediate states and error states</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*try48skh59oBn0dbz-6IXA.png" /><figcaption>Account Section</figcaption></figure><ul><li><strong>Order Details</strong>: In some cases when the user directly navigates to the order details screen and taps on Help Button, we display a bottom sheet to show the intermediate states and error states</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AImKE_9A6qTy85ABUexFGQ.png" /><figcaption>Order Detail Screen</figcaption></figure><ul><li><strong>Plan Settings:</strong> In this case when the user navigates to his plan detail screen and opens the plan settings, we fire the install request for the HelpCentre module and show the intermediate and error states to the user.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSRTIf0uNKRTV7a_WPSDNg.png" /><figcaption>Plan Settings Bottom Sheet</figcaption></figure><h4>Common Errors we encountered during downloading DFM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3kY27juSNInFOWEB2knFg.png" /></figure><h4><strong><em>References</em></strong></h4><ul><li><a href="https://medium.com/androiddevelopers/dependency-injection-in-a-multi-module-project-1a09511c14b7">https://medium.com/androiddevelopers/dependency-injection-in-a-multi-module-project-1a09511c14b7</a></li><li><a href="https://medium.com/androiddevelopers/patterns-for-accessing-code-from-dynamic-feature-modules-7e5dca6f9123">https://medium.com/androiddevelopers/patterns-for-accessing-code-from-dynamic-feature-modules-7e5dca6f9123</a></li><li><a href="https://developer.android.com/guide/app-bundle/playcore">https://developer.android.com/guide/app-bundle/playcore</a></li><li><a href="https://medium.com/mindorks/dynamic-feature-modules-the-future-4bee124c0f1">https://medium.com/mindorks/dynamic-feature-modules-the-future-4bee124c0f1</a></li><li><a href="https://developer.android.com/training/dependency-injection/dagger-multi-module">https://developer.android.com/training/dependency-injection/dagger-multi-module</a></li></ul><h3>Acknowledgements</h3><p>I would like to thank my colleagues for helping me implement this cool feature, you can reach out to them at <a href="https://twitter.com/@supriya36319772"><strong><em>Supriya Saha</em></strong></a><strong><em>,</em></strong> <a href="https://twitter.com/nuron142"><strong><em>Sunil Kumar</em></strong></a><strong><em>. </em></strong>And thanks to <a href="https://twitter.com/amsanjeev"><strong><em>Amrit Sanjeev</em></strong></a><strong><em> </em></strong>for the guidance :)</p><blockquote><em>I’m Sarabjeet (</em><a href="https://twitter.com/savvisingh"><strong><em>savvisingh</em></strong></a><em>) from front-end team at Swiggy. If you enjoyed learning about this and want to be a part of an exciting tech culture then head to </em><a href="https://careers.swiggy.com/"><strong><em>https://careers.swiggy.com/</em></strong></a><em> we are hiring</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83019ebfa980" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/exploring-dynamic-feature-modules-at-swiggy-83019ebfa980">Exploring Dynamic Feature Modules at Swiggy</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Swiggy uses In-App Update API for better App adoption]]></title>
            <link>https://medium.com/swiggy-bytes/how-swiggy-uses-in-app-update-api-for-better-app-adoption-dc04d2f62e0e?source=rss-e28fb631a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc04d2f62e0e</guid>
            <category><![CDATA[swiggy-tech]]></category>
            <category><![CDATA[swiggy-mobile]]></category>
            <category><![CDATA[swiggy-android]]></category>
            <category><![CDATA[swiggy-engineering]]></category>
            <dc:creator><![CDATA[Sarabjeet Singh]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 06:13:59 GMT</pubDate>
            <atom:updated>2019-09-25T06:13:59.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3S_8HtwNC6G5X4ik9mHOg.png" /><figcaption>source: <a href="https://undraw.co/">https://undraw.co/</a></figcaption></figure><p>I am sure everyone has faced the problem where we want the user to update the App ASAP because we want the user to try new features, or there are some critical bug/crash/security patches with the new update, but still there are those 1% users who haven’t updated the app. To tackle this problem Google team came up with a new feature at Google I/O, one of the most exciting In-App Updates (IAU) API which lets the user update the app without redirecting them to Play Store and user can keep using the app while the update is happening in background.</p><p>We at <a href="https://careers.swiggy.com/"><strong>Swiggy</strong></a>, <em>an online hyperlocal food delivery marketplace</em>, have used this API to get more user adoption for the latest app version. In this article, we will be talking about the recommended approach for implementing In-App Update API using code snippets. I will also cover how Swiggy has implemented the In-App Update Flow in the App.</p><h3>In-App update (IAU)</h3><p>The IAU is a feature of Android Play Core library, that allows you to provide a prompt to the user to offer them an update for the latest app version. In simple words, it provides an option to the user which says that an update for the app is available and the user can select if they are interested in updating the app or not.</p><p>Not only that, it provides an option to download the update of the app in the background and once downloaded, install the update and restart the app and the user don’t have to do anything.</p><p>The Play Core Library offers two ways of implementing the in-app update in our mobile application with completely different user experiences:</p><ol><li>The <a href="https://developer.android.com/guide/app-bundle/in-app-updates"><strong>Flexible flow</strong></a> prompts users to download an update in the background and install it at their convenience. It is meant to be used in situations when it is still okay for a user to use an older version of the app even though a new one has been released.</li><li>The <a href="https://developer.android.com/guide/app-bundle/in-app-updates"><strong>Immediate flow</strong></a> requires users to download and install an update before continuing using the app. It is meant to be used in situations when it is crucial for developers to prevent usage of the app before the update is applied.</li></ol><blockquote><strong><em>Note: The IAU feature is available for API level 21 or above and is only available to those apps which are on the play store.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*Lv0GKjSH0kCtG63a2wqtfw.gif" /></figure><p>They say practice makes a person perfect not theory, so let’s get to the code, shall we?</p><h3>Check for update availability</h3><p>Before we can go ahead with either of the flows first we need to check whether there is an update available from play store for our app</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4694af14a0da6b8d4bf9cfa838b25fcf/href">https://medium.com/media/4694af14a0da6b8d4bf9cfa838b25fcf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzEwlvyH1daer3FMRNYsyA.png" /><figcaption>An example of flexible update flow</figcaption></figure><p>We start by creating an Instance of <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateManager.html"><strong>AppUpdateManager</strong></a> class which is responsible for handling the information around our application information. Using the instance of AppUpdateManager we get an <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateInfo.html"><strong>AppUpdateInfo</strong></a> object which contains the information about whether we should trigger an update.</p><p>For checking the update state we use <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateInfo.html#updateAvailability()"><strong><em>updateAvailability</em></strong></a><strong><em>()</em></strong> method which returns a value that represents the update state. This can be either:</p><ul><li>UNKNOWN</li><li>UPDATE_AVAILABLE</li><li>UPDATE_IN_PROGRESS</li><li>DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS</li></ul><p>If update is available we need to check which type of update flow is allowed for our app <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateInfo.html#isUpdateTypeAllowed(int)"><strong><em>isUpdateTypeAllowed(updateType </em></strong></a><strong><em>:Int</em></strong><a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateInfo.html#isUpdateTypeAllowed(int)"><strong><em>)</em></strong></a> it can be either</p><ul><li>AppUpdateType.FLEXIBLE</li><li>AppUpdateType.IMMEDIATE</li></ul><p>Similarly, we have methods like <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateInfo.html#availableVersionCode()"><strong><em>availableVersionCode</em></strong></a><strong><em>() </em></strong>which gives us the version code of available update, <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateInfo.html#installStatus()"><strong><em>installStatus</em></strong></a><strong><em>()</em></strong> which tells us the current install status.</p><h3>Start an update</h3><p>Now that we have the information we need to determine whether or not an app update is available, we’re going to trigger the update flow. We can do this by making use of the <a href="http://eManager.html#startUpdateFlowForResult(com.google.android.play.core.appupdate.AppUpdateInfo,%20int,%20android.app.Activity,%20int)"><strong><em>startUpdateFlowForResult</em></strong></a><strong><em>()</em></strong> method that comes with the <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateManager.html"><strong>AppUpdateManager</strong></a> class. When we call this we just need to pass:</p><ul><li>The AppUpdateInfo instance that we previously retrieved</li><li>The AppUpdateType that we want to trigger (<strong>IMMEDIATE</strong> or <strong>FLEXIBLE</strong>)</li><li>The context for the current component</li><li>A request code so that cancellations/failures can be caught within the calling component</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be13871cb6a96b98a66ee3111d7cf8b9/href">https://medium.com/media/be13871cb6a96b98a66ee3111d7cf8b9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZrSIvrE2LXrs_Bzg0O5ww.png" /><figcaption>An example of an immediate update flow</figcaption></figure><blockquote><strong>Remember: Each </strong><strong>AppUpdateInfo instance can be used to start an update only once. To retry the update in case of failure, you need to request a new </strong><strong>AppUpdateInfo and check again that the update is available and allowed.</strong></blockquote><p>While doing the update, you can handle the update related failure or cancellation by using the <strong><em>onActivityResult() </em></strong>as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ae139dfb77f3eb8f88a860f8632dd5a/href">https://medium.com/media/2ae139dfb77f3eb8f88a860f8632dd5a/href</a></iframe><p>Here we are getting the <strong><em>MY_REQUEST_CODE </em></strong>from the appUpdateManager. Following are the request codes that you get in the <strong><em>onActivityResult</em></strong>:</p><ul><li><strong>RESULT_OK: </strong>You will get this if the user has accepted the request for an update.</li><li><strong>RESULT_CANCELED: </strong>The user has canceled the update or denied for the update.</li><li><strong>RESULT_IN_APP_UPDATE_FAILED: </strong>Some error has occurred during the update. It may be some error from the user side or some other error.</li></ul><h3>Flexible In-App Update(IAU)</h3><p>A flexible IAU can be done by using the <strong>AppUpdateType.FLEXIBLE </strong>while starting an update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d51e0d27229ecf885ccc95164a71bf4c/href">https://medium.com/media/d51e0d27229ecf885ccc95164a71bf4c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kPkTGKh5vYUhqxtX6ieXw.png" /></figure><p>This will prompt the user with a dialog with options for updating the app and canceling the update if the user chooses to cancel the dialog we will get the result in onActivtyResult with resultCode <strong>RESULT_CANCELED</strong>. If the user chooses to update the app, the download will start in the background and we can listen to the install progress by registering <a href="https://developer.android.com/reference/com/google/android/play/core/install/InstallStateUpdatedListener.html"><strong>InstallStateUpdatedListener</strong></a> to the AppUpdateManager instance. This contains a single callback, <a href="https://developer.android.com/reference/com/google/android/play/core/listener/StateUpdatedListener.html#onStateUpdate(StateT)"><strong><em>onStateUpdated</em></strong></a><strong><em>()</em></strong>, which will pass us an instance of the InstallState class. From this we can make use of:</p><p><strong><em>installStatus</em>()</strong> — returns us an <strong>InstallStatus</strong> value that represents the current state of the update. This can be one of:</p><ul><li><em>UNKNOWN</em></li><li><em>REQUIRES_UI_INTENT</em></li><li><em>PENDING</em></li><li><em>DOWNLOADING</em></li><li><em>DOWNLOADED</em></li><li><em>INSTALLING</em></li><li><em>INSTALLED</em></li><li><em>FAILED</em></li><li><em>CANCELLE</em>D</li></ul><p><strong><em>installErrorCode()</em></strong> — returns us an <strong>InstallErrorCode</strong> that represents the error state of the install</p><ul><li>NO_ERROR</li><li>NO_ERROR_PARTIALLY_ALLOWED</li><li>ERROR_UNKOWN</li><li>ERROR_API_NOT_AVAILABLE</li><li>ERROR_INVALID_REQUEST</li><li>ERROR_INSTALL_UNAVAILABLE</li><li>ERROR_INSTALL_NOT_ALLOWED</li><li>ERROR_DOWNLOAD_NOT_PRESENT</li><li>ERROR_INTERNAL_ERROR</li></ul><p><strong><em>packageName()</em></strong> — returns us the package name that the install status applies to</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f8b491b2358f62815628753be0cddb/href">https://medium.com/media/e5f8b491b2358f62815628753be0cddb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hQLojHN13XRkmnWQ2E0GQ.png" /></figure><p>Once we detect that the InstallStatus represents the <strong>DOWNLOADED</strong> state, we are required to restart the app so that the update can be installed. You can initiate the restart by calling <a href="https://developer.android.com/reference/com/google/android/play/core/appupdate/AppUpdateManager.html#completeUpdate()"><strong><em>completeUpdate</em></strong></a><strong><em>()</em></strong><em>,</em> but you might want to display a prompt(snackbar/dialog or any UI element) to allow users to confirm explicitly that he or she is ready to relaunch the app right now. When this is called, a full-screen UI will be displayed from the play core library and the app will be restarted in the background so that the update can be installed. The app will then be restarted with the update applied.</p><p>Similarly, we should also check for install Status when the app is coming back to the foreground in this case the update is downloaded in the background.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a7118755c9976d6108cd44b0e6a0d1a/href">https://medium.com/media/5a7118755c9976d6108cd44b0e6a0d1a/href</a></iframe><h3>How Swiggy Uses Flexible IAU Flow</h3><p>As a part of an EAP, we integrated IAU Flexible flow(recommended implementation) in the app. We show a crouton to the user on HomeScreen for every new update, In addition to that, we show a consistent update option in our Accounts Section with current install state like Downloading, Pending, Cancelled. Once the update is downloaded we show a Snackbar to restart the app which installs the update. I have attached some screenshots for the reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RkD594Q364DGr9JE7Mclg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hQLojHN13XRkmnWQ2E0GQ.png" /></figure><p>Let’s speak about the numbers. We have enabled the IAU for a week and seen <strong>16% conversion in terms of Click to Impression ratio</strong> and close to<strong> .7 Million Users updated the app</strong> through this, We have seen a huge increase in adoption rate for the new Rollouts as a result of integrating IAU Flow API in Swiggy App.</p><h4>Smart Config for IAU</h4><p>To make sure we show it at the right time to User we added few smart checks at our End like</p><ul><li>Show it only <strong>X times</strong> to User</li><li>If the user has canceled/dismissed it show it after <strong>X days</strong></li><li><strong>Reset</strong> all these values post app updates</li><li>All the values mentioned are configured from the <strong>server</strong> and can be changed without app release</li></ul><p>We were also <strong>featured in Google I/O 19</strong> for implementing it during EAP</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ffd.xuwubk.eu.org%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2Fo_oUeciBknU%3Ffeature%3Doembed%26start%3D939&amp;url=https%3A%2F%2Ffd.xuwubk.eu.org%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3Do_oUeciBknU&amp;image=https%3A%2F%2Ffd.xuwubk.eu.org%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2Fo_oUeciBknU%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/7f6db0eff003e878c4932a5027714b00/href">https://medium.com/media/7f6db0eff003e878c4932a5027714b00/href</a></iframe><p>The IAU API is now available to all developers. Check out the <a href="https://developer.android.com/guide/app-bundle/in-app-updates">documentation</a> to learn more.</p><h4>Acknowledgments</h4><p>I want to thank my colleagues for their contribution in this article and integrating this cool feature in Swiggy App. Thanks to <a href="https://twitter.com/anupamshr">Anupam Shrivastava</a>, <a href="https://twitter.com/karan_techno">Karandeep Singh</a> :)</p><blockquote>I am Sarabjeet (<a href="https://twitter.com/savvisingh">savvisingh</a>) from front-end team at Swiggy, If you enjoyed learning about this and want to be a part of an exciting tech culture then head to <a href="https://careers.swiggy.com/">https://careers.swiggy.com/</a> we are hiring :)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc04d2f62e0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/how-swiggy-uses-in-app-update-api-for-better-app-adoption-dc04d2f62e0e">How Swiggy uses In-App Update API for better App adoption</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimising scrolling performance with Litho]]></title>
            <link>https://medium.com/swiggy-bytes/optimising-scrolling-performance-with-litho-59db9819c583?source=rss-e28fb631a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/59db9819c583</guid>
            <category><![CDATA[litho]]></category>
            <category><![CDATA[swiggy-engineering]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[swiggy-mobile]]></category>
            <dc:creator><![CDATA[Sarabjeet Singh]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 12:33:27 GMT</pubDate>
            <atom:updated>2019-11-07T06:32:27.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZ9dudimptMjxgFDh9z9qA.png" /><figcaption>Image source: <a href="https://undraw.co/">undraw.co</a></figcaption></figure><p>We at Swiggy wanted to improve our scroll performance which directly impacts our key App metrics. While trying different solutions we came across Litho framework, which provides fine grained recycling of the views, Flatter view hierarchies and asynchronous layout calculations which improves overall scroll performance.</p><p>And after using Litho for the Swiggy app, we saw huge performance gains. So, here we are, sharing how Litho has been useful to us and how it could be useful to you too.</p><h3>What is it?</h3><blockquote><strong><em>Litho is a library which allows us to create complex UIs declaratively with optimisations under the hood.</em></strong></blockquote><p><strong>Inspired from React </strong>Litho is backed by <a href="https://facebook.github.io/yoga/">Yoga</a> which is a cross-platform layout engine, based on the FlexBox architecture. It allows you to write highly-optimised Android views through a simple functional API based on Java annotations. With Litho, you build your UI in terms of <em>components</em> instead of interacting directly with traditional Android views. The data is passed to the component as variables annotated with <strong>Props</strong>. Props are immutable values. We can only use it, but cannot change it. But how do you handle state changes without changing data? For that we use annotation called <strong>State</strong>. States can hold values that may change. We can create states inside components. And perform an event to change the state, which causes the component to re-render to make the changes visible.</p><p>In Litho, we declare what the UI should look like<strong> </strong>and at compile time, it generates the actual code for the component. Finally all the components are wrapped inside a root ViewGroup called LithoView.</p><h3>How Litho Optimizes</h3><ul><li><strong>Asynchronous layout : </strong>Litho can measure and layout your UI ahead of time without blocking the UI thread. Litho can drop the UI thread constraint imposed by Android.</li><li><strong>Flatter view hierarchies :</strong> Litho uses <a href="https://yogalayout.com/docs">Yoga</a> for layout and automatically reduces the number of ViewGroups that your UI contains. This, in addition to Litho’s text optimizations, allows for much smaller view hierarchies and improves both memory and scroll performance.</li><li><strong>Fine-grained recycling</strong> : With Litho, each UI item such as text, image, or video is recycled individually. As soon as an item goes off screen, it can be reused anywhere in the UI and pieced together with other items to create new UI elements. Such recycling reduces the need of having multiple view types and improves memory usage and scroll performance.</li></ul><h3>Some Key Points to Consider</h3><ul><li>Litho’s primary use case is <strong><em>RecyclerViews</em></strong> with complex content as it delivers great scroll performance even with complex items with a wide variety of content, which is quite challenging to achieve using traditional Android views.</li><li>If you are planning to use dynamic UIs with animations and gestures, it’s a bit complex to implement in Litho but as engineers, we can make it work. I will try to cover those topics in my next blog.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*sDdPp0dzoIYptJ0cIrqnsA.gif" /></figure><p><em>Okay enough of theory lets dive into some action and kill some white walkers</em></p><h3>Adding Litho to your project</h3><p><strong>Step 1</strong> : Add these lines to your <em>build.gradle</em> file</p><pre>dependencies {<br>  // ...<br>  // Litho<br>  implementation &#39;com.facebook.litho:litho-core:0.23.0&#39;<br>  implementation &#39;com.facebook.litho:litho-widget:0.23.0&#39;<br>  compileOnly &#39;com.facebook.litho:litho-annotations:0.23.0&#39;</pre><pre>annotationProcessor &#39;com.facebook.litho:litho-processor:0.23.0&#39;</pre><pre>// SoLoader<br>  implementation &#39;com.facebook.soloader:soloader:0.5.1&#39;</pre><pre>}</pre><p><strong>Step 2</strong>: Initialize SoLoader in your Application onCreate</p><pre>override fun onCreate() {<br>    super.onCreate();</pre><pre>SoLoader.init(this, false);<br>  }</pre><p><strong>Step 3</strong>: Let’s start with our Hello World Text</p><pre>override fun onCreate(savedInstanceState: Bundle?){<br>    super.onCreate(savedInstanceState);</pre><pre>var context = new ComponentContext(this);</pre><pre>var component = Text.create(context)<br>        .text(&quot;Hello World&quot;)<br>        .textSizeDip(50)<br>        .textColorRes(R.color.<em>black</em>)<br>        .textAlignment(Layout.Alignment.ALIGN_CENTER)<br>        .backgroundRes(R.color.white)<br>        .build();</pre><pre>setContentView(LithoView.create(context, component));<br>}</pre><p>If you run this code, Litho will generate a Text component in your layout with hello world text.</p><h4><strong>Step 4</strong> : Creating Component Spec Class</h4><p>A <em>layout spec</em> is the logical equivalent of a composite view on Android. It simply groups existing components together. A component spec class will be processed to generate a <a href="https://fblitho.com/javadoc/com/facebook/litho/ComponentLifecycle">ComponentLifecycle</a> subclass with the same name as the spec but without the <em>Spec</em> suffix. For example, a MyComponentSpec spec generates a MyComponent class. Litho identifies the Spec class using the @LayoutSpecannotation. In the onCreateLayout method we will return a ComponentLayout with all the child views in it, if any.</p><pre>@LayoutSpec<br>object MyComponentSpec {</pre><pre>@OnCreateLayout<br>    fun onCreateLayout(componentContext: ComponentContext,<br>                       @Prop title: String,<br>                       @Prop(optional = true) subtitle: String,<br>                       @Prop clickAction: () -&gt; Unit): Component {</pre><pre>return Column.create(componentContext)<br>            .backgroundRes(R.color.<em>white</em>)<br>            .paddingRes(YogaEdge.BOTTOM, R.dimen.<em>dimen_16dp</em>)<br>            .paddingRes(YogaEdge.TOP, R.dimen.<em>dimen_16dp</em>)<br>            .paddingRes(YogaEdge.START, R.dimen.<em>dimen_16dp</em>)<br>            .paddingRes(YogaEdge.END, R.dimen.<em>dimen_16dp</em>)<br>            .alignItems(YogaAlign.CENTER)<br>            .clickHandler(MyComponent.onItemClick(componentContext, clickAction))<br>            .child(<br>                Text.create(componentContext)<br>                .text(title)<br>                .textSizeSp(40f)<br>            )<br>            .child(<br>                if(!subtitle.<em>isNullOrEmpty</em>()){<br>                    Text.create(componentContext)<br>                        .text(subtitle)<br>                        .textSizeSp(40f)<br>                }else{<br>                    null<br>                }<br>            )<br>            .build()<br>    }</pre><pre>@OnEvent(ClickEvent::class)<br>    fun onItemClick(c: ComponentContext, @Param clickAction: () -&gt; Unit) {<br>        clickAction?.invoke()<br>    }<br>}</pre><p>Litho will generate MyComponent class which exposes create() method that returns the appropriate Component Builder for the @Props that we declared in our spec class.</p><p><strong>Step 5:</strong></p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)</pre><pre>var component = MyComponent.create(ComponentContext(this))<br>        .title(&quot;Hello World&quot;)<br>        .subtitle(&quot;My first Component class&quot;)<br>        .clickEvent <strong>{ </strong>Toast.makeText(this,&quot;Hurray&quot;,  Toast.<em>LENGTH_SHORT</em>).<em>show </em><strong>}</strong></pre><pre>setContentView(LithoView.create(context, component))<br>}</pre><h4>Some practical Pointers on using Litho Components</h4><ul><li>In the above component spec we are using <strong><em>Column</em></strong> which is equivalent to LinearLayout with vertical orientation, we can also use <strong><em>Row </em></strong>which is LinearLayout with horizontal Orientation.</li><li><strong><em>alignItems()</em></strong> describes how to align children along the cross axis of their container, in our case we are using Column so the cross axis will be horizontal and in case of Row it will be Vertical.</li><li><strong><em>justifyContent()</em></strong> describes how to align children along the main axis of their container, in case of Column the main axis is vertical and in case of Row it is horizontal.</li><li>All components can handle the following events by default: ClickEvent, LongClickEvent, and TouchEvent. This means all layout builders have an EventHandler prop named clickHandler, longClickHandler, and touchHandler respectively.</li><li>I know it’s hard to create components without seeing how will it render like the XML editor, but you can visualize it by heading to the <a href="https://yogalayout.com/playground"><strong><em>https://yogalayout.com/playground</em></strong></a></li></ul><p>Hope you got the hang of above code, if not don’t worry take a break, read it again with a cup of coffee, but come back because the next part is interesting one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*dSxcd3SDmEQoIzX6zc0Kag.gif" /><figcaption>Okeeey Lets burn some Lannisters, just kidding I like Jaime</figcaption></figure><h3>GroupSection Spec class</h3><blockquote><strong><em>Sections API</em></strong><em> is a feature which supports most of RecyclerView features under the hood including calculating changes in data using DiffUtil on a background thread. The Sections API allows creating complex RecyclerViews easily.</em></blockquote><p><strong>Step 1:</strong> Add these dependencies to your <em>build.gradle</em> file</p><pre>dependencies {</pre><pre>// Sections<br>  implementation &#39;com.facebook.litho:litho-sections-core:0.23.0&#39;<br>  implementation &#39;com.facebook.litho:litho-sections-widget:0.23.0&#39;<br>  compileOnly &#39;com.facebook.litho:litho-sections-annotations:0.23.0&#39;</pre><pre>annotationProcessor &#39;com.facebook.litho:litho-sections-processor:0.23.0&#39;</pre><pre>}</pre><h4>Step 2: Creating GroupSectionSpec class</h4><pre>@GroupSectionSpec<br>object MyComponentSectionSpec{</pre><pre>@OnCreateChildren<br>    fun onCreateChildren(sectionContext: SectionContext,<br>                         @Prop headerTitle: String,<br>                         @Prop dataSet: ArrayList&lt;ListItem&gt;): Children {<br>        return Children.create()<br>            .child(<br>                SingleComponentSection.create(sectionContext)<br>                    .component(<br>                        Text.create(sectionContext)<br>                            .text(headerTitle)<br>                            .build()))<br>            .child(<br>                DataDiffSection.create&lt;ListItem&gt;(sectionContext)<br>                    .data(dataSet)<br>                    .renderEventHandler(MyComponentSection.onRender(sectionContext)))<br>                .build()<br>    }</pre><pre>@OnEvent(RenderEvent::class)<br>    fun onRender(sectionContext: SectionContext, @FromEvent model: ListItem): RenderInfo {<br>        val renderInfo = ComponentRenderInfo.create()<br>        renderInfo.component(MyComponent.create(sectionContext)<br>                .title(model.<em>title</em>)<br>                .subtitle(model.<em>subTitle</em>)<br>                .clickEvent <strong>{ </strong>model.<em>action</em><strong>}</strong>)</pre><pre>return renderInfo.build()<br>    }<br>}</pre><p>SingleComponentSection is a core section that renders a single component, and DataDiffSection is specifically used to render components backed by a list of models.</p><p>In the above example, we are creating a GroupSection to Render a list of components backed by a list of models just like we do in RecyclerView Adapters. If we have more than one view type we can render different component based on our model object in our onRender method just like below.</p><pre>@OnEvent(RenderEvent::class)<br>fun onRender(sectionContext: SectionContext, @FromEvent model: BaseModel): RenderInfo {<br>    val renderInfo = ComponentRenderInfo.create()<br>    when(model){<br>        is ItemTypeOne -&gt; {<br>            renderInfo.component(MyComponent.create(sectionContext)<br>                .title(model.<em>title</em>)<br>                .subtitle(model.<em>subTitle</em>)<br>                .clickEvent <strong>{ </strong>model.<em>action</em><strong>}</strong>)<br>        }<br>        is ItemTypeTwo -&gt; {<br>            renderInfo.component(MyComponent.create(sectionContext)<br>                .title(model.<em>title</em>)<br>                .subtitle(model.<em>subTitle</em>)<br>                .clickEvent <strong>{ </strong>model.<em>action</em><strong>}</strong>)<br>        }<br>    }</pre><pre>return renderInfo.build()<br>}</pre><h4><strong>Step 3:</strong></h4><p>We can use the above section with RecyclerCollectionComponent to render our list. <a href="https://fblitho.com/javadoc/com/facebook/litho/sections/widget/RecyclerCollectionComponent">RecyclerCollectionComponent</a> takes a section as a prop and renders a RecyclerView containing whatever UI the section outputs. It also manages updates and changes from the section such as refreshing data and performing tail fetches. We’re not using any data fetching here so let&#39;s disable PTR (pull to refresh) for this tutorial. In your activity, change the component definition to:</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)</pre><pre>val sectionContext = SectionContext(this)<br>    var component = RecyclerCollectionComponent.create(sectionContext)<br>        .disablePTR(true)<br>        .itemAnimator(null)<br>        .overScrollMode(View.<em>OVER_SCROLL_NEVER</em>)<br>        .clipChildren(false)<br>        .clipToPadding(false)<br>        .section(<br>            MyComponentSection.create(sectionContext)<br>                .dataSet(itemList)<br>                .headerTitle(&quot;Component List&quot;)<br>                .build())<br>        .build()</pre><pre>setContentView(LithoView.create(context, component))<br>}</pre><ul><li>If we want a <strong><em>horizontal list</em></strong> we can supply a ListRecyclerConfiguration with Horizontal Mode to our component and we can also provide the snapping mode for our scrollable List, other snapping options are SNAP_NONE, SNAP_TO_END, SNAP_TO_CENTER</li></ul><pre>var component = RecyclerCollectionComponent.create(sectionContext)<br>    .recyclerConfiguration(<br>        <strong>ListRecyclerConfiguration&lt;SectionBinderTarget&gt;(LinearLayoutManager.<em>HORIZONTAL</em>,<br>            false,<br>            SnapUtil.SNAP_TO_START)</strong>)</pre><ul><li>For <strong><em>GridView</em></strong> we have to pass <a href="https://fblitho.com/javadoc/com/facebook/litho/sections/widget/GridRecyclerConfiguration">GridRecyclerConfiguration</a> and in our GroupSection Spec onRender method we have to specify the span size for items otherwise, it won’t display anything tried that :P</li></ul><pre>RecyclerCollectionComponent.create(sectionContext)<br>    .recyclerConfiguration(<br>        <strong>GridRecyclerConfiguration&lt;SectionBinderTarget&gt;(GridLayoutManager.<em>HORIZONTAL</em>,<br>            2,<br>            false)</strong>)</pre><p>Setting span size for GridView Item, depending on your requirements you can change the span size</p><pre>@OnEvent(RenderEvent::class)<br>    fun onRender(sectionContext: SectionContext, @FromEvent model: ListItem): RenderInfo {<br>        <strong>val renderInfo = ComponentRenderInfo.create()<br>    .spanSize(1)</strong><br>        renderInfo.component(MyComponent.create(sectionContext)<br>                .title(model.<em>title</em>)<br>                .subtitle(model.<em>subTitle</em>)<br>                .clickEvent <strong>{ </strong>model.<em>action</em><strong>}</strong>)</pre><pre>return renderInfo.build()<br>    }</pre><p>Litho seems quite friendly for someone like me who hasn’t worked with FlexBox. The learning curve is not too steep, so after some use, you will get the hang of it. For me, I prefer prefer Litho than XML — yes, there are missing components like ViewPager, Buttons and others components, but you can create them on your own!</p><p>While you wait for the next part on how to write your own missing components, feel free to check out interesting components like <a href="https://fblitho.com/docs/mount-specs">MountSpecs</a> &amp; learn more about <a href="https://fblitho.com/docs/state">States</a>. And that’s it folks! Thanks for reading! I hope you enjoyed this article and found it useful, if so please hit the Clap button. Let me know your thoughts in the comments section.</p><p>Happy coding!</p><h4>References</h4><ul><li><a href="https://fblitho.com/">https://fblitho.com/</a></li><li><a href="https://therubberduckdev.wordpress.com/2017/11/27/basics-of-facebook-litho-a-declarative-ui-framework-for-android/">https://therubberduckdev.wordpress.com/2017/11/27/basics-of-facebook-litho-a-declarative-ui-framework-for-android/</a></li><li><a href="https://code.fb.com/android/components-for-android-a-declarative-framework-for-efficient-uis/">https://code.fb.com/android/components-for-android-a-declarative-framework-for-efficient-uis/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59db9819c583" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swiggy-bytes/optimising-scrolling-performance-with-litho-59db9819c583">Optimising scrolling performance with Litho</a> was originally published in <a href="https://medium.com/swiggy-bytes">Swiggy Bytes — Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>