<?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 David Chen on Medium]]></title>
        <description><![CDATA[Stories by David Chen on Medium]]></description>
        <link>https://medium.com/@diousk507?source=rss-bdbea8cb9bcf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*BgNVH1BytbKvtSd-0ll6Iw.jpeg</url>
            <title>Stories by David Chen on Medium</title>
            <link>https://medium.com/@diousk507?source=rss-bdbea8cb9bcf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:33:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diousk507/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[Things you may want to know about paging-compose]]></title>
            <link>https://medium.com/@diousk507/things-you-may-want-to-know-about-paging-compose-bab56c0e1a8a?source=rss-bdbea8cb9bcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/bab56c0e1a8a</guid>
            <category><![CDATA[paging-library]]></category>
            <category><![CDATA[paging-compose]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[David Chen]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 04:34:57 GMT</pubDate>
            <atom:updated>2022-09-13T04:38:06.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bFKdPA_szkruYhCk" /><figcaption>Photo by <a href="https://unsplash.com/@sodacheese?utm_source=medium&amp;utm_medium=referral">Jouwen Wang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jetpack paging library has been existed in the original Android view system for a while. With the paging-compose library, we can leverage the power of paging functionalities like we do in the view system.</p><p>Before we dig into it, let’s see a basic setup of paging-compose (v1.0.0-alpha15)</p><ol><li>Create a simple <em>PagingSoruce</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f7bbb4ed5eb1d07b808df2164bde7e/href">https://medium.com/media/43f7bbb4ed5eb1d07b808df2164bde7e/href</a></iframe><p>2. Create the flow of PagingData inside ViewModel</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2de614471f741f4f98f8c039f48f5d63/href">https://medium.com/media/2de614471f741f4f98f8c039f48f5d63/href</a></iframe><p>From the UI part, we create a composable called FirstScreen to display the paging data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6dd415c4c7e47ba545aa3c134d1a8c2/href">https://medium.com/media/e6dd415c4c7e47ba545aa3c134d1a8c2/href</a></iframe><p>Here is the result:</p><p><a href="https://giphy.com/embed/2YpdgVAMskO6BBX9fb">Animated GIF - Find &amp; Share on GIPHY</a></p><p>You may notice that there’s a TextButton to go to the SecondScreen which simply display a button to navigate back, and we control this behavior by a remember state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647589c0f05845476a1587065a8060b8/href">https://medium.com/media/647589c0f05845476a1587065a8060b8/href</a></iframe><p><strong>Here comes the problem:</strong> If we scroll the list at the FirstScreen, click the button to navigate to the SecondScreen, and navigate back, the scrolling state is lost! And the list on the UI is also reset to the top. This behavior is the same when you are using the Jetpack Navigation library to navigate between screens.</p><blockquote><em>There’s a related issue tracker about this: </em><a href="https://issuetracker.google.com/issues/177245496"><em>https://issuetracker.google.com/issues/177245496</em></a></blockquote><p>From the issue tracker, we can see that the main reason why the scrolling state is reset is because the LazyListState we passed to the LazyColumn is lost when the FirstScreen is recreated.</p><p>We can add some log to the FirstScreen to see what happened:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d5b09fe4017682a3a52fe9010f3f4f7/href">https://medium.com/media/4d5b09fe4017682a3a52fe9010f3f4f7/href</a></iframe><pre>// scrolling down<br>D: item 1, androidx.compose.foundation.lazy.LazyListState@86ce3c<br>D: item 2, androidx.compose.foundation.lazy.LazyListState@86ce3c<br>D: item 3, androidx.compose.foundation.lazy.LazyListState@86ce3c<br>// navigate to SecondScreen<br>D: FirstScreen disposed, item 3, androidx.compose.foundation.lazy.LazyListState@86ce3c<br>// navigate back<br>D: item 0, androidx.compose.foundation.lazy.LazyListState@4c8d551</pre><p>After navigate back to the FirstScreen, the LazyListState is recreated with initial value 0.</p><p>If we want to keep the list state between navigation, the setup like this is not working. Let’s explore some possible solutions to this problem.</p><h4>Solution 1:</h4><p>Move the initialization of LazyListState &amp; LazyPagingItems to the upper layer, which is inside MyTheme block so they will not be affected by the re-creation of the composable, the FirstScreen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f67a8226b373314949bf03bc3315a20/href">https://medium.com/media/5f67a8226b373314949bf03bc3315a20/href</a></iframe><p>And the composable signature becomes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c14115684172a52754058bcc33d6fc/href">https://medium.com/media/40c14115684172a52754058bcc33d6fc/href</a></iframe><p>This solution works if your app only has a small amount of pages that need pagination so you don’t mess up the upper layer.</p><h4>Solution 2:</h4><p>Keep the <strong>collectAsLazyPagingItems</strong>() inside the FirstScreen and save the LazyListState to ViewModel</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01d82b579fe2892e6a6b80d9d4606f46/href">https://medium.com/media/01d82b579fe2892e6a6b80d9d4606f46/href</a></iframe><p>Because of the fact that <strong>collectAsLazyPagingItems</strong>() will create a new LazyPagingItems, the refresh state inside will begin with a Loading state. Therefore we need a loading indicator or placeholder to handle the state.</p><p>And here is the result (the screen blinks when navigate back)</p><p><a href="https://giphy.com/embed/9rRAfs8Dr8yJMAiyBz">Animated GIF - Find &amp; Share on GIPHY</a></p><h4>Why the screen blinks?</h4><p>Like we just said, when <strong>collectAsLazyPagingItems</strong>() get calls, it internally creates a new LazyPagingItems and its itemSnapshotList inside is initialized with an empty item list.</p><p>The implementation of <strong>collectAsLazyPagingItems</strong>()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4721f51b3fa6f68b17240f5c08ee74b9/href">https://medium.com/media/4721f51b3fa6f68b17240f5c08ee74b9/href</a></iframe><p>Only after collectPagingData() gets called, the cached PagingData from the Flow will then be updated to the itemSnapshotList inside LazyPagingItems.</p><p>So how can we solve the blink?</p><p>My approach is to also cache the LazyPagingItems in ViewModel, so after FirstScreen is recreated, the LoadState &amp; its itemSnapshotList will not change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6047db3bea011b2d6433bb09d232a76b/href">https://medium.com/media/6047db3bea011b2d6433bb09d232a76b/href</a></iframe><p><strong>Is the problem solved?</strong></p><p>No, because we’re using the cached LazyPagingItems in second round of composition, the previous collections of flow inside of collectAsLazyPagingItems() are cancelled. There’s no calls to start the collection of the Flows&lt;PagingData&gt; &amp; Flow&lt;CombinedLoadState&gt; so the pagination won’t work if we try to scroll around the item list in order to trigger a page load.</p><p>Since the suspend functions collectPagingData() &amp; collectLoadState() are both marked as internal inside LazyPagingItems, we can’t manually launch the collection of flow. Making a copy version of LazyPagingItems seemed inevitable.</p><p>Once we have a copy of LazyPagingItems, we can launch the collection of flow by ourself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/373c87422651a49443e55abd2588e95e/href">https://medium.com/media/373c87422651a49443e55abd2588e95e/href</a></iframe><p>Now the state of paging list will be restored after navigation between screens.</p><p>That’s it. Hope it helps.</p><p>If you have other solutions, please leave a comment to let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bab56c0e1a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Scope for Multiple Activities in Dagger 2]]></title>
            <link>https://medium.com/@diousk507/custom-scope-for-multiple-activities-in-dagger-2-5b02968af4f8?source=rss-bdbea8cb9bcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b02968af4f8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[David Chen]]></dc:creator>
            <pubDate>Tue, 26 May 2020 01:47:28 GMT</pubDate>
            <atom:updated>2020-08-14T01:03:13.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Scope across Multiple Activities with Dagger 2</h3><p>In dagger 2, especially dagger-android, we usually define our component by using <em>ContributesAndroidInjector</em> annotation, which is a great annotation to save our time writing boilerplate code for creation of <em>SubComponent</em> and <em>SubComponent.Factory.</em></p><p>If we need a scope to achieve “local singleton” object, we can add a custom scope `@PerActivity` and defined as following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1df5b958bc6cf937eae17d70300fdcd9/href">https://medium.com/media/1df5b958bc6cf937eae17d70300fdcd9/href</a></iframe><p>In the above code, we can have a “local singleton” object with type `SomeObject` inside `SomeActivity`. We can even inject this `SomeObject` inside the attached fragments within this activity. The object will remain the same one(that’s why we call it “local singleton”) and this object will be garbage-collected after the activity is destroyed.</p><blockquote><strong>How about multiple activities sharing a custom scope?</strong></blockquote><p>Look at the sample code above, in order to use custom scope, we need to annotate it on the <em>Component</em>(or <em>SubComponent</em>), but with dagger-android, the component for activity/fragment is auto-generated by <em>ContributesAndroidInjector</em>, and it’s built for a single activity or fragment which means that we can not just use <em>ContributesAndroidInjector </em>to achieve “a custom scope for multiple activities”.</p><p>This problem is addressed in the official code lab about using dagger in Android app, in the chapter#13</p><p><a href="https://codelabs.developers.google.com/codelabs/android-dagger">Using Dagger in your Android app - Kotlin</a></p><p>The key here to have a custom scope across multiple activities is sharing a singleton object, and manage the lifecycle of the <em>SubComponent</em> manually inside that singleton object.</p><p>So, let’s go back to dagger’s <em>SubComponent</em> to find out how it work!</p><p>TLDR; You can access the sample project here:</p><p><a href="https://github.com/diousk/ScopedWithDagger">diousk/ScopedWithDagger</a></p><p>Assume that we have three screens: <em>LoginActivity</em>, <em>MainActivity</em> and <em>SettingActivity</em>. And we want a custom scope called <em>SessionScope</em> which covers MainActivity and SettingActivity for logged-in user. In this case the diagram will be like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiW4GJCmi1zAo1z1kLncZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82t0RVdS0DnOBeSUZy2YrA.jpeg" /></figure><p>Ok, first create a normal AppComponent</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bace64bfe1a0c1ef5d9396804dfd9276/href">https://medium.com/media/bace64bfe1a0c1ef5d9396804dfd9276/href</a></iframe><p>with class ActivityBuilder and class AppSubcomponents as following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bc265753dbd036c021a232a6eeb0325/href">https://medium.com/media/6bc265753dbd036c021a232a6eeb0325/href</a></iframe><p>and the SessionManager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a5518a7c8b7984a260cfaf193c861ff/href">https://medium.com/media/7a5518a7c8b7984a260cfaf193c861ff/href</a></iframe><p>Because <em>LoginActivity</em> does not belong to <em>SessionScope</em>, we declare it in the <em>ActivityBuilder</em> of <em>AppComponent</em>.</p><p>The <em>SessionComponent</em> is a subcomponent of <em>AppComponent</em> and we need to add the custom scope (<em>SessionScope</em>) on it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a893791e013fa4e772eee7eae30b2d76/href">https://medium.com/media/a893791e013fa4e772eee7eae30b2d76/href</a></iframe><p>Note here we need to expose the `<strong><em>DispatchingAndroidInjector&lt;Any&gt;</em></strong>` as an injector (auto-generated from <em>ContributesAndroidInjector</em> after build) so that we can inject our activities with custom scope</p><p>Then, create a base activity class for any activities using SessionScope</p><p>Here we call it DaggerSessionActivity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5759070c2528b74528817852e5690bff/href">https://medium.com/media/5759070c2528b74528817852e5690bff/href</a></iframe><p>The basic dagger setup is almost done!</p><p>Now we start to build our activities.</p><p>The first one is LoginActivity, which is nothing more than an entry to MainActivity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cbfac9fbbc6947a3035b57fd32cc56c/href">https://medium.com/media/7cbfac9fbbc6947a3035b57fd32cc56c/href</a></iframe><p>Note that before <em>startActivity()</em>, we invoke <strong><em>sessionManager.loginUser()</em></strong> to create <em>SessionComponent</em> inside the singleton <em>sessionManager</em> so that we can use it to inject the activities using <em>SessionScope</em>.</p><p>Then, create MainActivity which inherits DaggerSessionActivity we mentioned above</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a22c71760bf22580e477ff5dca8f747/href">https://medium.com/media/6a22c71760bf22580e477ff5dca8f747/href</a></iframe><p>And the SettingActivity for logout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cb09bc292ea34b8c9d754d0679a50bc/href">https://medium.com/media/2cb09bc292ea34b8c9d754d0679a50bc/href</a></iframe><p>In the SettingActivity, we provide a logout button to simply set null to the <em>sessionComponent</em> inside <em>SessionManager</em> to release the reference to it. (also the allocated objects under the scope)</p><p>We inject a simple class called SessionPrefs into MainActivity and SettingActivity, and from the logs printed out we can check that both of the objects’ memory address are the same, which means that we can provide a scoped-singleton object to be used across multiple activities under the same scope.</p><pre>main sessionPrefs = com.diousk.scopeddagger.deps.SessionPrefs@1af2dd7<br>setting sessionPrefs = com.diousk.scopeddagger.deps.SessionPrefs@1af2dd7</pre><p>If we click the logout button, and login again. The SessionPrefs object will be recreated and will persist until next logout in this lifetime of application</p><p>That’s it!</p><p>Thanks for your reading!</p><p>references:</p><ul><li><a href="https://codelabs.developers.google.com/codelabs/android-dagger">Using Dagger in your Android app - Kotlin</a></li><li><a href="https://android.jlelse.eu/dagger-android-in-an-all-activity-architecture-cab2c3571625">Dagger-Android in an all activity architecture</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b02968af4f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Coroutine: Await For Listener]]></title>
            <link>https://medium.com/@diousk507/kotlin-coroutine-await-for-listener-5148c85e001f?source=rss-bdbea8cb9bcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5148c85e001f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[David Chen]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 13:23:09 GMT</pubDate>
            <atom:updated>2020-04-10T01:16:27.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KRYI6mCi56W9JGzh" /><figcaption>Photo by <a href="https://unsplash.com/@argyriou?utm_source=medium&amp;utm_medium=referral">Denys Argyriou</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometime, we need to use the callback or listener pattern to wait for the task to be processed and then continue to deal with the result in the callback.</p><p>For example, in Android, if we want to wait for the View to be laid out, we might write some code like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef8aefc867b5ea9fd89b9ee41d326481/href">https://medium.com/media/ef8aefc867b5ea9fd89b9ee41d326481/href</a></iframe><p>Though the most of these lines can be auto-generated, it still occupied a certain space of this class which make it not quite readable :(</p><p>With the power of <strong>Kotlin Coroutine </strong>we can transform the listener pattern to a suspend function, and use it with ease!</p><p>Here is how it works, first we need to define a suspend function with <strong><em>suspendCancellableCoroutine</em></strong> as an extension method of View:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8a5fbd3c46c8e21221f029b16fb0575/href">https://medium.com/media/e8a5fbd3c46c8e21221f029b16fb0575/href</a></iframe><p>And then we add the listener inside <strong><em>suspendCancellableCoroutine</em></strong> like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7052544a414ff3678ec680f3618cc9c3/href">https://medium.com/media/7052544a414ff3678ec680f3618cc9c3/href</a></iframe><p>Now, let’s say, in fragment’s <strong><em>onViewCreated()</em></strong>, if we want to wait for the root view to be laid out, we can now use the function just defined:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc6a6807cff7969aad129abeaeeef7e/href">https://medium.com/media/1dc6a6807cff7969aad129abeaeeef7e/href</a></iframe><p>In the above sample code, the line 4 can suspend the current coroutine (<strong><em>without blocking the main thread</em></strong>) until the <strong><em>awaitLayout() </em></strong>is resumed.</p><p>Here is another example to wait for the virtual keyboard dismissed by adapting another open source project:(<a href="https://github.com/yshrsmz/KeyboardVisibilityEvent">https://github.com/yshrsmz/KeyboardVisibilityEvent</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c57f66b6c626f1b612670bce42602ebe/href">https://medium.com/media/c57f66b6c626f1b612670bce42602ebe/href</a></iframe><p>with the similar wrapping of callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/519b0cca7a99020c62611f5a4e0b07f3/href">https://medium.com/media/519b0cca7a99020c62611f5a4e0b07f3/href</a></iframe><p>That’s it! We can now use <strong><em>awaitKeyboardHidden()</em></strong> in Fragment to wait for the keyboard dismissed, and continue to do things just in the next line.</p><p>The code is more readable and simple, right? :)</p><p>There’re more useful suspend functions like <strong><em>Animator.awaitEnd()</em></strong>, <strong><em>RecyclerView.awaitScrollEnd()</em></strong> where you can find in the Chris Banes’s great article:</p><p><a href="https://chris.banes.dev/2019/12/03/suspending-views/">Suspending over Views</a></p><p>Hope this article can help you handle the callback/listener gracefully and thanks for your reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5148c85e001f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using FragmentFactory with Dagger 2]]></title>
            <link>https://medium.com/@diousk507/using-fragmentfactory-with-dagger-2-c3ec136c860d?source=rss-bdbea8cb9bcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ec136c860d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[fragmentfactory]]></category>
            <dc:creator><![CDATA[David Chen]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 10:23:56 GMT</pubDate>
            <atom:updated>2020-05-11T03:45:44.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DAOLxPNbq-_aWXsf" /><figcaption>Photo by <a href="https://unsplash.com/@elistoo?utm_source=medium&amp;utm_medium=referral">Chenyu Jiang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>FragmentFactory has been released since <em>androidx.fragment:fragment:1.1.0</em> and it allows us to manage the initiation of fragment and remove the requirement to have a default no-argument constructor for fragment.</p><p>In combination with Dagger 2 we can finally inject our dependencies into fragment by transforming the FragmentFactory into a injectable class and no longer need to handle the creation of fragment everywhere.</p><p>The final result will be like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf291a5aaf99c4997fd54aec8d3057cf/href">https://medium.com/media/bf291a5aaf99c4997fd54aec8d3057cf/href</a></iframe><p>And your fragment (we use constructor injection here)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa8dc2f3aee9c6c8f74fb99ec913da5/href">https://medium.com/media/8fa8dc2f3aee9c6c8f74fb99ec913da5/href</a></iframe><h3><strong>TL;DR</strong></h3><p><a href="https://github.com/diousk/FragmentFactoryWithDagger">diousk/FragmentFactoryWithDagger</a></p><p>Note: If you’re not familiar with Dagger 2, please refer to other online resources to learn the concept of it. Or you can begin from the Android Developers’ website. This article will not cover the fundamentals of Dagger 2.</p><p><a href="https://developer.android.com/training/dependency-injection/dagger-basics">Dagger basics | Android Developers</a></p><p>Let’s start!</p><p>The first step is to setup the gradle dependencies:</p><pre>// AndroidX KTX<br>implementation &quot;androidx.core:core-ktx:$core_ktx_version&quot;<br>implementation &quot;androidx.fragment:fragment-ktx:$fragment_ktx_version&quot;</pre><pre>// LiveData &amp; ViewModel &amp; Lifecycle KTX<br>implementation&quot;androidx.lifecycle:lifecycle-extensions:$lifecycle_version&quot;<br>implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version&quot;<br>implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version&quot;</pre><pre>// Dagger - for dependency injection<br>implementation &quot;com.google.dagger:dagger:$dagger2_version&quot;<br>implementation &quot;com.google.dagger:dagger-android:$dagger2_version&quot;<br>implementation &quot;com.google.dagger:dagger-android-support:$dagger2_version&quot;<br>kapt &quot;com.google.dagger:dagger-compiler:$dagger2_version&quot;<br>kapt &quot;com.google.dagger:dagger-android-processor:$dagger2_version&quot;</pre><p>Then, setup a custom fragment factory to inject the dependency of Class-Fragment map</p><blockquote>(like the custom ViewModelProvider.Factory for ViewModel):</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53e35a4d8b950656e7d77e341254c112/href">https://medium.com/media/53e35a4d8b950656e7d77e341254c112/href</a></iframe><p>In order to bind fragment into our DaggerFragmentFactory, we need to define a <strong>FragmentKey</strong> annotation (like we define ViewModelKey for ViewModel) to use the multi-binding feature of dagger</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a0e05309434859a0105853f49c24eee/href">https://medium.com/media/9a0e05309434859a0105853f49c24eee/href</a></iframe><p>Then, we define the binding of DaggerFragmentFactory to FragmentFactory in another separated dagger module so that we can include this FragmentBuilder for any activity requiring DaggerFragmentFactory to initiate fragments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80e4bbcf7e1d8b1d8191a526579a659/href">https://medium.com/media/f80e4bbcf7e1d8b1d8191a526579a659/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7428b5f4fe8d2e5376354d577fdf2766/href">https://medium.com/media/7428b5f4fe8d2e5376354d577fdf2766/href</a></iframe><p>Now, let’s define the DummyBuilder for our fragment.</p><p>In this module, we have to define the multi-binding of the DummyFragment to Fragment at the <strong>DummyBuilder layer</strong> because it’s the activity(in our sample) which will inject FragmentFactory and will try to find out the injectable Fragment classes.</p><p>So don’t misplace the binding of Fragment or it may result in a compile error</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6430469909d61b210d0e95292d12fe7/href">https://medium.com/media/e6430469909d61b210d0e95292d12fe7/href</a></iframe><p>DummyFragment is defined with an additional dependency which can be automatically provided from dagger graph. That means you can add any dependency for this fragment as long as the dependency existing in your dagger graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4ef8e5cf29fad4f3d2b0977455afd6e/href">https://medium.com/media/d4ef8e5cf29fad4f3d2b0977455afd6e/href</a></iframe><p>We are almost there!</p><p>In our activity, we have to inject fragment factory so that we can set it to fragment manager before super.onCreate() like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68f0c052606d5f366bce6f58130d1040/href">https://medium.com/media/68f0c052606d5f366bce6f58130d1040/href</a></iframe><p>But you’ll receive a runtime error from the above code</p><pre>Caused by: kotlin.UninitializedPropertyAccessException: lateinit property fragmentFactory has not been initialized</pre><p>That’s because the injection of dagger happens in the super.onCreate(savedInstanceState), so we can not get the fragmentFactory initialized.</p><p><strong>Solution</strong>: create a mimic of DaggerAppCompatActivity except exposing the stage after injection but before super.onCreate()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/881f6b27f82d7ee8655f7aae5e106630/href">https://medium.com/media/881f6b27f82d7ee8655f7aae5e106630/href</a></iframe><p>Finally, in our MainActivity we can simply use <em>supportFragmentManager</em> to launch fragment as usual but without creation of fragment here</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c6ec9fd6cf755281e8937487d974cc5/href">https://medium.com/media/5c6ec9fd6cf755281e8937487d974cc5/href</a></iframe><p>That’s it.</p><p>Every time when we need a fragment to be injected with dependencies, we simply add those dependencies to its constructor and define a binding of XXXFragment to Fragment in the builder module and just use the fragment manager to launch our fragment</p><p>If you have a better way to combine FragmentFactory with Dagger, please feel free to leave a comment.</p><p>Thanks for your reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ec136c860d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>