<?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 Alexander Sitnikov on Medium]]></title>
        <description><![CDATA[Stories by Alexander Sitnikov on Medium]]></description>
        <link>https://medium.com/@sitnikovalexander?source=rss-4080ac9d2cab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*d6h1NcDBQvUHDwpa0fBGoQ.jpeg</url>
            <title>Stories by Alexander Sitnikov on Medium</title>
            <link>https://medium.com/@sitnikovalexander?source=rss-4080ac9d2cab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:41:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sitnikovalexander/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[Deep dive into Dagger generated code (part 3)]]></title>
            <link>https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-3-2d1593ad154?source=rss-4080ac9d2cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d1593ad154</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alexander Sitnikov]]></dc:creator>
            <pubDate>Sat, 02 May 2020 10:42:24 GMT</pubDate>
            <atom:updated>2020-05-04T12:50:22.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0XA6hw4KH7Kl-NaSIQfqw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@lum3n-44775?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Lum3n</a> from <a href="https://www.pexels.com/photo/gray-and-black-folding-pocket-knife-168804/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>In previous blog posts, we looked at how different features of Dagger are implemented under the hood. We refactored and converted the generated code from Java to Kotlin to get a better understanding of it. In this blog post, we cover two more big topics: scopes and subcomponents.</p><p><em>In order to follow the rest of the article, it is highly recommended to read part 1 and 2 of the series.</em></p><ul><li><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-1-58f3cb9563de">Deep dive into Dagger generated code (part 1)</a></li><li><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-2-13de4781b49d">Deep dive into Dagger generated code (part 2)</a></li></ul><h3>Scopes</h3><p>Scoping is a mechanism defined in JSR-330 like so: “If a scope annotation is present, the injector may retain the instance for possible reuse in a later injection”. Also, JSR-330 has one predefined scope annotation — @Singleton. In Dagger, we can annotate classes with an inject constructor or module methods with scope annotation to indicate, that this instance will be a singleton within the component. This component has to have this scope annotation applied to it as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c2d199a0c9276647c7df7ee492d05b/href">https://medium.com/media/64c2d199a0c9276647c7df7ee492d05b/href</a></iframe><p>To create singleton instances, Dagger will use internal DoubleCheck class. This class implements the famous double-check java technique that is used for creating singleton instances and implementing lazy semantics. Being Provider itself, DoubleCheck accepts a Provider as a constructor parameter and saves the instance returned from a wrapped Provider on the first call to get() of DoubleCheck. Also, DoubleCheck implements Lazy, so it can be used to create Lazy as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71a55c6d7b0e5e6e67c17498a3222fcb/href">https://medium.com/media/71a55c6d7b0e5e6e67c17498a3222fcb/href</a></iframe><p>For readability sake, let’s replace DoubleCheck with methods, that take advantage of Kotlin trailing lambda syntax.</p><p>8. Replace DoubleCheck.provider() with createSingleton()</p><p>9. Replace DoubleCheck.lazy() with createLazy()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4628d03e1b8c14a586e8d04701cff23/href">https://medium.com/media/d4628d03e1b8c14a586e8d04701cff23/href</a></iframe><p>After applying these methods to the previously defined component, we get a bit more readable code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27e5105e599688b00028e637e39980c7/href">https://medium.com/media/27e5105e599688b00028e637e39980c7/href</a></iframe><h4>Custom scope annotation</h4><p>So that’s what happens when we use predefined @Singleton annotation. Let’s see how things will change when we define a custom @Scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5cfdbce2a4a1f43c4a51ff8c69e4db1/href">https://medium.com/media/c5cfdbce2a4a1f43c4a51ff8c69e4db1/href</a></iframe><p>Dagger generates absolutely the same code, as when we defined a @Singleton. This means singletons will be created in the component regardless of what scope annotation is used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aeac584787edfad230257b8ea90ae04/href">https://medium.com/media/2aeac584787edfad230257b8ea90ae04/href</a></iframe><h4>@Reusable</h4><p>Additionally, there’s special scope annotation in Dagger — @Reusable. Applying this scope indicates that the object returned by a binding may be (but might not be) reused.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73193c1df5057db8497e9d8ffeb84029/href">https://medium.com/media/73193c1df5057db8497e9d8ffeb84029/href</a></iframe><p>@Reusable scoped instances are stored in a Dagger’s internal SingleCheck class. Unlike DoubleCheck, this class doesn’t use synchronization to get an instance from the wrapped Provider, so it can provide two different instances when used in a multithreaded environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c125f7fdf0530668e9cfee1abec3371/href">https://medium.com/media/2c125f7fdf0530668e9cfee1abec3371/href</a></iframe><h4>Lazy</h4><p>Dagger Lazy is implemented the same way as singletons, but with one significant difference: singleton providers are stored inside the component, and Lazy providers created on demand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0923c6216a8bd0c21ccd8da4638a8d4/href">https://medium.com/media/d0923c6216a8bd0c21ccd8da4638a8d4/href</a></iframe><p>Lazy behavior can be demonstrated in the following snippet. For every Lazy instance the same value is returned for all subsequent uses of that Lazy. But each created Lazy is independent, and remembers its value in isolation of other Lazy instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cfbc682170ae0b239a3a46e8ac6d508/href">https://medium.com/media/8cfbc682170ae0b239a3a46e8ac6d508/href</a></iframe><p>In the implementation, we can clearly see that singleton is stored as a field in the component, and Lazy is created for each invocation of createLazy().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f156d9c0762b30cfcd772502ca73139/href">https://medium.com/media/1f156d9c0762b30cfcd772502ca73139/href</a></iframe><h4>Using Lazy to break circular dependencies</h4><p>Lazy can be used to break circular dependencies. For example, imagine the following situation. ApiSerivce uses HttpClient to do network calls. HttpClient uses Authenticator to do authentication. And Authenticator uses ApiService to do the auth call. Here we have a clear circular dependency — there’s no way to instantiate these classes if they all have @Inject constructors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ccd968b22a4d4581794e6f27a712c9/href">https://medium.com/media/66ccd968b22a4d4581794e6f27a712c9/href</a></iframe><p>We can break the circular dependency in two ways: either remove one of the @Inject constructors or inject a Lazy (or Provider) into one of the classes. One of the limitations of this approach is the inability to use lazily injected class inside the constructor (or init block). Also, we should probably make lazily injected class to be a singleton inside the component, so that only one instance of that class would be instantiated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb45758c6f8b6531eb1f4248a7150cc/href">https://medium.com/media/3cb45758c6f8b6531eb1f4248a7150cc/href</a></iframe><p>In the component implementation below we can see that apiServiceProvider initialized with DelegateFactory. It is an internal Dagger class that stitches Provider/Lazy indirection based dependency cycles. What does this mean?</p><p>We need to defer apiServiceProvider initialization until we have the httpClientProvider instance, but we need an actual apiServiceProvider instance to create authenticatorProvider. That’s why we create the empty DelegateFactory first and initialize it later with setDelegate() static method after all the other providers are created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae0f2d5aae392ef1414b17ab8be889f7/href">https://medium.com/media/ae0f2d5aae392ef1414b17ab8be889f7/href</a></iframe><p>The closest analog to DelegateFactory in Kotlin is lateinit fields. We can replace DelegateFactory with two fields in component — first is an actual provider, and the second is lateinit delegate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1edd2a6ed65da4e557a267f3cf8c8d09/href">https://medium.com/media/1edd2a6ed65da4e557a267f3cf8c8d09/href</a></iframe><h3>Subcomponents</h3><p>As per Dagger documentation, subcomponents are components that inherit and extend the object graph of a parent component. This is one of their main features — you can get any binding from the parent component without explicitly declaring it. We can create instances of subcomponent by defining a method in the parent component, that returns either subcomponent instance or its Builder\Factory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/509d858e4808524f8ffe70096b8218d3/href">https://medium.com/media/509d858e4808524f8ffe70096b8218d3/href</a></iframe><p>We can see that the subcomponent was generated as an inner class inside the parent component. That’s why subcomponents have full access to the parent component graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fccf1c8e056c04c0f4733e0bd90b8d11/href">https://medium.com/media/fccf1c8e056c04c0f4733e0bd90b8d11/href</a></iframe><h4>Subcomponents in modules</h4><p>Another way to create subcomponents is in the modules by passing either subcomponent or its Builder\Factory as an argument of a @Provides method. In that case, you’ll have to declare a subcomponent class in a subcomponents parameter of @Module annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eac798c56feb75c458f0c3ce32e8882/href">https://medium.com/media/9eac798c56feb75c458f0c3ce32e8882/href</a></iframe><p>For the case above, the generated subcomponent factory will be passed to the module’s provider method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23096bf96e36613f1815723b8da61e31/href">https://medium.com/media/23096bf96e36613f1815723b8da61e31/href</a></iframe><h4>Conclusion</h4><p>That’s it for the series. You can find all of the code in the <a href="https://github.com/aasitnikov/DaggerScopesSampleApp">GitHub repository</a>. I hope that after reading this series you will have a better understanding of the Dagger generated code. You can try to open some project with Dagger and check if you could navigate in the generated code. See you around.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d1593ad154" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-3-2d1593ad154">Deep dive into Dagger generated code (part 3)</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[Deep dive into Dagger generated code (part 2)]]></title>
            <link>https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-2-13de4781b49d?source=rss-4080ac9d2cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/13de4781b49d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Alexander Sitnikov]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 20:31:50 GMT</pubDate>
            <atom:updated>2020-05-02T11:15:42.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0XA6hw4KH7Kl-NaSIQfqw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@lum3n-44775?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Lum3n</a> from <a href="https://www.pexels.com/photo/gray-and-black-folding-pocket-knife-168804/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>In the previous blog post, we looked at the different types of classes Dagger generates. Converting the generated code from Java to Kotlin with some additional refactoring removes visual noise and helps us understand it better. In this blog post, we continue to dive into how different features are implemented in Dagger — component instantiation, members injection, qualifiers and multi-bindings. Most of those features were introduced after the initial release of Dagger, and were build on top of things discussed in the part 1 of the series.</p><p><em>In order to follow the rest of the article, it is highly recommended to read part 1 of the series.</em></p><p><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-1-58f3cb9563de">Deep dive into Dagger generated code (part 1)</a></p><h4>Component instantiation</h4><p>In Dagger there are two ways to instantiate the component — Builder and Factory. By default, Dagger generates a Builder. We can make Dagger create a custom implementation of a Builder — for that, we have to create an inner interface and annotate it with @Component.Builder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f925055ea6d5d68c5474ef849dae6e9/href">https://medium.com/media/5f925055ea6d5d68c5474ef849dae6e9/href</a></iframe><p>As a result, the generated Builder will implement the declared interface. For every setter method, there will be fields generated inside Builder. Also static builder() method will be generated in the component, that will return an instance of that builder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcae0556076d1b3c7512d32cfd0bd56e/href">https://medium.com/media/bcae0556076d1b3c7512d32cfd0bd56e/href</a></iframe><p>When using Builder, you can forget to call one of the setter methods, causing exceptions during runtime. To avoid that, Dagger v2.22 added the ability to create @Component.Factory for component instantiation. This Factory is stateless and has a single method, so the program will fail at compile time instead of runtime if you forget to declare some of the component dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75a69db3f8a55e2fe7001691c24966cb/href">https://medium.com/media/75a69db3f8a55e2fe7001691c24966cb/href</a></iframe><p>As we can see below, this single method just instantiates the component, without any temporary fields.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4237a7de0ce4068fc6c9d1cc9dbc7ba8/href">https://medium.com/media/4237a7de0ce4068fc6c9d1cc9dbc7ba8/href</a></iframe><h4>@BindsInstance</h4><p>One of the most useful features of the custom Builder or Factory is the ability to define @BindsInstance. It allows passing external instances to the component without declaring modules or dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12214a821083102ef1982f7b2dd91516/href">https://medium.com/media/12214a821083102ef1982f7b2dd91516/href</a></iframe><p>The instance passed into CustomFactory.customCreate() will be stored in the field inside the component, thus making it singleton for this component.</p><p>In the generated code you can notice that stringProvider property is defined using InstanceFactory. It is the internal Dagger class that simply returns the same instance for every get().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50824630b1c2a2fafb587ae08bd4acda/href">https://medium.com/media/50824630b1c2a2fafb587ae08bd4acda/href</a></iframe><p>To further simplify things, let’s add a new rule.</p><p>5. Replace all generated factories and InstanceFactory with a lambda</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85884ff035ccb790906c024b674c7907/href">https://medium.com/media/85884ff035ccb790906c024b674c7907/href</a></iframe><h4>@Component.Factory and component fields</h4><p>So we can use @Component.Factory to pass stateful modules, dependencies, and binds instances to a component. Let’s create a factory that accepts all of the different types of parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba9828b538d067ab34aaf066d3e6d6cb/href">https://medium.com/media/ba9828b538d067ab34aaf066d3e6d6cb/href</a></iframe><p>As we can see below, all of them are stored as fields inside the component. With that in mind, you can treat all the parameters of @Component.Factory as constructor parameters of the component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b55d5de5b9c729e1ed3513d949580a1/href">https://medium.com/media/8b55d5de5b9c729e1ed3513d949580a1/href</a></iframe><h3>Members injection</h3><p>Sometimes we don’t control the lifecycle of an object — we can’t instantiate it in @Provides method or add @Inject constructor to it. This is when members-injection comes to the rescue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef0e0eff88d43794807970b9d1c4c868/href">https://medium.com/media/ef0e0eff88d43794807970b9d1c4c868/href</a></iframe><p>Dagger generates a members-injector for classes with @Inject applied to a field or a method. MembersInjector is the functional interface (lambda) defined in Dagger, and it is implemented by all generated members-injectors.</p><pre>public interface MembersInjector&lt;T&gt; {<em><br>    </em>void injectMembers(T instance);<br>}</pre><p>Let’s take a look inside the generated members-injector. For every member of the target class, Dagger generates a static method (injectRepository() in the example above), that assigns the given instance to a field or calls a setter of a target object. Inside the overridden injectMembers() method, all of these generated methods are called using instances, obtained from Providers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c07bbbc6ee9e8adade606875e515de66/href">https://medium.com/media/c07bbbc6ee9e8adade606875e515de66/href</a></iframe><h4>Super members injection</h4><p>There is some special case when class inheritance involved in member’s injection. Let’s take a look at the simple case when one class extends other, and both have members with @Inject.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b13eb712305904585dc21c60e050f0fd/href">https://medium.com/media/b13eb712305904585dc21c60e050f0fd/href</a></iframe><p>In that case injectMembers() of generated ChildActivity_MembersInjector calls a static injectString() of parent’s BaseActivity_MembersInjector. So we can come to a conclusion, that if you pass subtype instance to the supertype members-injection method, members of subtype will not be injected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adfc9f3ab029867e4ff40dff43cbc2bb/href">https://medium.com/media/adfc9f3ab029867e4ff40dff43cbc2bb/href</a></iframe><p>Now let’s take a look at the generated component. Private methods injectBaseActivity() and injectChildActivity() have the same content as in the generated injectMembers() of the respective class, and also return the injected instance (because you can make component’s members-injection methods return the injected instance).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/775fb2ecbd54d9ce405acad0953bc815/href">https://medium.com/media/775fb2ecbd54d9ce405acad0953bc815/href</a></iframe><p>Again, inlining all the calls, the generated component code becomes easy to grasp.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9c466734a93a85e1a06f1c416c17877/href">https://medium.com/media/b9c466734a93a85e1a06f1c416c17877/href</a></iframe><h4>Methods of component</h4><p>To summarize, we can declare different types of methods in a component: provision methods and members-injection methods. We can also create methods, that return Provider and MembersInjector directly.</p><p>Two main purposes of the component are to create new instances and inject instances into members of already created objects, and they are accomplished by declaring provision and members-injection methods in the component interface. We can also declare methods, that directly return Provider or MembersInjector, to defer the effect of their actions. Let’s take a look at all of those methods in one component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad9e9364bf34cfe3247a90fd3c719c61/href">https://medium.com/media/ad9e9364bf34cfe3247a90fd3c719c61/href</a></iframe><p>Because Provider and MembersInjector are functional interfaces, and Kotlin has build-in support for them, we can define some new rules of conversion:</p><p>6. Replace Provider&lt;T&gt; and Factory&lt;T&gt; with () -&gt; T</p><p>7. Replace MembersInjector&lt;T&gt; with (T) -&gt; Unit</p><p>You can notice, that methods of the same purpose are almost identical, but in one case they are executed immediately, and in the other lambda is returned to be executed on demand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea77d14d2c558936fd396c6c7cda4cfa/href">https://medium.com/media/ea77d14d2c558936fd396c6c7cda4cfa/href</a></iframe><h4>@Binds methods</h4><p>In the early versions, there was no way to tell Dagger to put implementations where interface was requested — one had to create @Provides method with one parameter of implementation type that returned interface type. That resulted in unnecessary factory generation. So, in Dagger v2.4 @Binds annotation was released.</p><p>@Binds methods are declared in modules and just tell Dagger to delegate bindings from superclass/interface to implementation. For example, suppose we have an interface — CharSequence, and some implementation — CharSequenceImpl. We can instruct Dagger to put CharSequenceImpl where CharSequence is requested by declaring an abstract @Binds method in the module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d2858b12f8d6dcb1f097f70699f72b/href">https://medium.com/media/c8d2858b12f8d6dcb1f097f70699f72b/href</a></iframe><p>A thing to note is that @Binds annotated methods are never called by the generated components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4625dbaf38592aa9a1c801b8d6b66ed4/href">https://medium.com/media/4625dbaf38592aa9a1c801b8d6b66ed4/href</a></iframe><p>There is one strange limitation in Dagger that @Binds methods are required to have different names, despite the fact that they are never called and no factories generated for them. If you find it inconvenient — upvote this <a href="https://github.com/google/dagger/issues/1587">issue</a>.</p><h3>Qualifiers</h3><p>@Qualifier is annotation defined in JSR-330. It is used to disambiguate between different instances of the same type. In Dagger, it can be applied to every place where binding is defined: @Provides and @Binds methods of a module, @BindsInstance of a Builder\Factory, provision method of a component dependency; or where binding is consumed: @Inject constructor parameter, @Provides method parameter, component’s provision method, @Inject to a field or a method.</p><p>JSR-330 defines one default qualifier annotation — @Named. Qualifiers can have annotation attributes — and @Named has one of type String. We can also create our own qualifier annotations — we just need to annotate it with @Qualifier.</p><p>Let’s take a look at the next example, where different types of qualifiers are applied to different targets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/961268aad5d139e88ab3ad9ccc3d1966/href">https://medium.com/media/961268aad5d139e88ab3ad9ccc3d1966/href</a></iframe><p>Note that qualifiers are just instructions for the Dagger compiler, they do not appear in the generated code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80cd34b4a818d31302554315048aad29/href">https://medium.com/media/80cd34b4a818d31302554315048aad29/href</a></iframe><h4>Kotlin properties and qualifiers</h4><p>You should be <strong>extra careful</strong> when using Kotlin properties with qualifiers. Consider the following component configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6716defd45caa1e44fc5edf1a47f16eb/href">https://medium.com/media/6716defd45caa1e44fc5edf1a47f16eb/href</a></iframe><p>This component won’t compile: Dagger’s annotation processor fails with [Dagger/MissingBinding] java.lang.String cannot be provided without an @Inject constructor or an @Provides-annotated method.</p><p>That’s because @Named annotation applied to property, and in Java, there are multiple elements, that correspond to Kotlin property declaration. By default, if both targets are applicable, annotation applies to a property instead of a field, so when compiled for JVM, it gets applied to a special method of the special DefaultImpls inner interface, not to the getter method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fef1271dea9c5bd904702eb89185c0ef/href">https://medium.com/media/fef1271dea9c5bd904702eb89185c0ef/href</a></iframe><p>To fix this, we need to do one of two things: either use a method or specify getter as an annotation target.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bca2df199668cf1838b8df214c5729fb/href">https://medium.com/media/bca2df199668cf1838b8df214c5729fb/href</a></iframe><p>To avoid issues of this kind, don’t use properties with qualifiers as component provision methods (and as component’s dependencies).</p><h4>Multibindings</h4><p>Multibindings is a feature, that allows you to accumulate bindings from one or multiple modules of component into a map (@IntoMap) or into a set (@IntoSet). When contributing to a map, you also have to define a key for binding — either by using one of the predefined annotations @StringKey, @LongKey, @IntKey or @ClassKey, or by creating custom annotation annotated with @MapKey.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e798afddc159f9bf0c8933362ad08f/href">https://medium.com/media/c5e798afddc159f9bf0c8933362ad08f/href</a></iframe><p>As we can see below, Dagger creates a map and a set using methods from @Provides modules. Keys for the map are statically defined in @StringKey annotations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d530b3a81f70ab516d481300c97b405/href">https://medium.com/media/4d530b3a81f70ab516d481300c97b405/href</a></iframe><h4>End of part 2</h4><p>In this blog post, we looked at component factory, member-injection, module binds, qualifiers, and multibindings. There are two more big topics to cover: scopes and subcomponents. You can find all of the examples in the <a href="https://github.com/aasitnikov/DaggerScopesSampleApp">GitHub repository</a>. See you next time!</p><p><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-3-2d1593ad154">Deep dive into Dagger generated code (part 3)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13de4781b49d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-2-13de4781b49d">Deep dive into Dagger generated code (part 2)</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[Deep dive into Dagger generated code (part 1)]]></title>
            <link>https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-1-58f3cb9563de?source=rss-4080ac9d2cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/58f3cb9563de</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Alexander Sitnikov]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 18:22:54 GMT</pubDate>
            <atom:updated>2020-05-02T11:15:41.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0XA6hw4KH7Kl-NaSIQfqw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@lum3n-44775?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Lum3n</a> from <a href="https://www.pexels.com/photo/gray-and-black-folding-pocket-knife-168804/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Dagger is one of the most complex DI frameworks for Java and Android out there. It comes with compile-time safety and fast runtime but has a steep learning curve and requires a lot of boilerplate code to setup. When using Dagger, our goal is to set it up to generate the code that would solve our DI needs. By understanding the code Dagger generates we can better understand how to configure it properly.</p><p>One of the problems is that the generated Dagger code can be quite verbose. Null-checks, explanatory messages and a lot of generated classes are essential for debugging and making it work in different scenarios but complicate the understanding when you read or debug it. Also, Dagger generates code in Java, which is by itself quite verbose.</p><p>In this series, we will <strong>convert the Dagger generated code from Java to Kotlin</strong> utilizing Kotlin language features to refactor and greatly simplify it for a better understanding of how it works.</p><h4>Example</h4><p>To get familiar with the process, let’s consider the following simple setup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6152185a9fec315d7747ce0bc21e1f3b/href">https://medium.com/media/6152185a9fec315d7747ce0bc21e1f3b/href</a></iframe><p>When we compile this, Dagger will generate a few classes, one of which is the implementation of the component — DaggerInteractorComponent. If we convert these generated classes to Kotlin, we could get something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f527808e159938937f657e660d1910f3/href">https://medium.com/media/f527808e159938937f657e660d1910f3/href</a></iframe><p>To simply create instances of an Interactor on-demand, Dagger generated 56 lines of code! Let’s apply some transformations to it to reduce verbosity:</p><ol><li>Remove all the null-checks and other assertions</li><li>Replace component Builder /Factory with a primary constructor with default parameters.</li><li>For every generated factory (such as InteractorModule_InteractorFactory), inline static methods into call sites.</li></ol><p>After applying these transformations, the result becomes quite concise and easy-to-understand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e64192e9e5fb3bcbd2993a65c22a55a/href">https://medium.com/media/4e64192e9e5fb3bcbd2993a65c22a55a/href</a></iframe><p>This is what the rest of the series will be about. First, we will start with some Dagger setup. Second, we’ll convert the generated code from Java to Kotlin using the rules defined above. And finally, when new code constructs are met, we will define new rules of conversion to produce even more concise code.</p><h3>Dagger’s main abstraction</h3><p>Object graph, generated by Dagger, is quite a complex thing. Bindings, defined in the component, can come from modules, from component’s dependencies and bound instances, from @Inject constructors, they can be scoped and unscoped. Such complexity should be simplified by using some sort of abstraction. The one Dagger heavily uses is the Provider interface, defined in JSR-330.</p><pre>public interface Provider&lt;T&gt; {<em><br>    </em>T get();<br>}</pre><p>Provider is a simple functional interface (aka lambda), that just returns some value. It can create a new instance for every invocation of get(), or it can return the same value over and over again, or it can do both — Provider just guarantees to return some value. Dagger often uses Providers in the presence of scopes (we will take a look at them later in the series), but in their absence Dagger optimizes the generated code and avoids creating Providers if possible.</p><p>There are many ways to add bindings to a component’s graph, to name a few:</p><ul><li>@Inject constructors</li><li>@Provides methods in modules</li><li>component dependencies</li></ul><p>For every one of the enumerated above ways Dagger will generate special Factory or Provider class. So let’s examine each one of them more closely.</p><h4>@Inject constructor</h4><p>Annotating a class constructor with @Inject allows Dagger to create instances of this class without additional configuration.</p><pre>class Repository @Inject constructor()</pre><p>For every class with the @Inject constructor, Dagger will generate a Factory (Factory interface extends Provider defined above). Let’s take a look at the generated factory for the Repository class.</p><p>For every class with the @Inject constructor, Dagger will generate a factory. Factory is the interface that extends Provider (<a href="https://github.com/google/dagger/blob/master/java/dagger/internal/Factory.java#L24-L34">javadoc</a>). Let’s take a look at the generated factory for the Repository class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d97148db111470ecffaf7f17cb182b7e/href">https://medium.com/media/d97148db111470ecffaf7f17cb182b7e/href</a></iframe><p>Every factory generated for the @Inject constructor has three methods. get() is a method, defined in the Provider interface, and it returns a new instance for every invocation. For that, it will delegate to the generated static method newInstance(), which creates that instance. Finally, the static create() method returns an instance of a factory.</p><p>Static methods are created mostly for simplifying the generated code and making it compile. For example, if a class has a package-private constructor, newInstance() makes it effectively public, and thus available for all the other generated code. create() simplifies obtaining an instance of the factory. In most cases, it just calls a constructor, but when a class has no dependencies, Dagger generates a singleton factory, like the Repository_Factory, and create() method just returns the object instance.</p><p>But it is a rare situation when @Inject is applied to the constructor without parameters. So let’s add a parameter to the constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4457df7d5bd407158c22791571dc17df/href">https://medium.com/media/4457df7d5bd407158c22791571dc17df/href</a></iframe><p>In that case, the generated factory will look a bit different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f7b0672d9beecf62dd87a1b4c03fcf/href">https://medium.com/media/87f7b0672d9beecf62dd87a1b4c03fcf/href</a></iframe><p>Now generated factory accepts one Provider instance for every parameter of the injected constructor (in the case above it was only one parameter). In the overridden get() method, the factory simply creates a new instance and uses given providers to resolve dependencies of that instance.</p><p>Returning to the component, if we inline that factory method call into it, we get this straightforward code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ae0d06bb565bbc8f0901969897aa10/href">https://medium.com/media/94ae0d06bb565bbc8f0901969897aa10/href</a></iframe><h4>Modules</h4><p>Modules are another way to define bindings. Every method annotated with @Provides annotation will add a new binding to the component. These methods can call other methods of a module and access its properties. Let’s take a look at the simple example of a module with one @Provides method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/900a02e942fb28f38e2a5754d2045405/href">https://medium.com/media/900a02e942fb28f38e2a5754d2045405/href</a></iframe><p>Dagger generates one factory for every @Provides method of a module. These factories are a bit different from @Inject constructor factories. First, newInstance() methods are renamed to match the @Provides method name, like createApiService(). Second, an additional parameter of the module instance is added to the constructor of the factory. And similar to @Inject constructor factories, they accept one Provider instance for every parameter of the @Provides method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adfcff06285ec553e8fb9a82612dab50/href">https://medium.com/media/adfcff06285ec553e8fb9a82612dab50/href</a></iframe><p>In the snippet above, create() method was omitted because it often just calls the constructor. So let’s add a new rule of conversion:</p><p>4. Static create() methods are inlined and replaced with a direct constructor call.</p><h4>Static methods in modules</h4><p>Class modules are fine when you need to convert external dependencies or untangle some complex relationships between objects. But in most cases, static methods in modules are more preferable, because they do not depend on the state of a module instance, and therefore the instance of the module is not needed to instantiate the object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/823eb4922ce30e2ef6ad7dea9d95613b/href">https://medium.com/media/823eb4922ce30e2ef6ad7dea9d95613b/href</a></iframe><p>Note that no instance of the module passed to the constructor of the generated factory. Effectively, static @Provides methods in object modules are kinda like @Inject constructors defined externally (but they do not support generics yet).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e768505bc47e25b27f010fab867026c5/href">https://medium.com/media/e768505bc47e25b27f010fab867026c5/href</a></iframe><h4>Dependencies</h4><p>Component dependency is a feature that allows adding external bindings from the dependency interface. When a type is used as a component dependency, each provision method on the dependency is bound as a provider. It is used mostly to get bindings from another component, but can also be used with the arbitrary interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a23c0d4163cb098bd01b40b81622578/href">https://medium.com/media/0a23c0d4163cb098bd01b40b81622578/href</a></iframe><p>If Dagger needs to create a provider for dependency, it will generate an inner Provider class for that dependency inside the component, otherwise, it will call the dependencies’ provision method directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0013acaa1c3f3ba8ce15978c9fb26288/href">https://medium.com/media/0013acaa1c3f3ba8ce15978c9fb26288/href</a></iframe><p>After simplifying, we get the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9eae06e85215a9197dce60e74f2b9e/href">https://medium.com/media/ea9eae06e85215a9197dce60e74f2b9e/href</a></iframe><h4>End of part 1</h4><p>In this blog post, we looked at the code Dagger generates in the presence of @Inject constructors and @Provides methods and learned about Provider and Factory interfaces. You can find all of the examples in the <a href="https://github.com/aasitnikov/daggerinternals">GitHub repository</a>. The next blog post will uncover even more features of Dagger: members-injection, module binds, qualifiers, and multibindings. In the meantime, you can check out an awesome blog post “<a href="https://medium.com/androiddevelopers/dagger-code-generation-cheat-sheets-6b4fa2da4e7a">Dagger code generation cheat sheets</a>” from Manuel Vivo.</p><ul><li><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-2-13de4781b49d">Deep dive into Dagger generated code (part 2)</a></li><li><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-3-2d1593ad154">Deep dive into Dagger generated code (part 3)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58f3cb9563de" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/deep-dive-into-dagger-generated-code-part-1-58f3cb9563de">Deep dive into Dagger generated code (part 1)</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[How to store scoped Dagger Components in Android applications]]></title>
            <link>https://proandroiddev.com/how-to-store-scoped-dagger-components-in-android-applications-4f3e86a5e957?source=rss-4080ac9d2cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3e86a5e957</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Alexander Sitnikov]]></dc:creator>
            <pubDate>Sat, 18 Jan 2020 12:14:45 GMT</pubDate>
            <atom:updated>2023-05-24T08:03:26.121Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a lot of articles explaining how to use scopes and create scoped components in Dagger 2, but hardly ever it is mentioned where to store those scoped components.</p><p>In a simple case, when there’s a single dagger component, we create it in the Application.onCreate() method and then store it in some static field. But that technique is hard to apply when there are scopes because they can be destroyed before application destroys.</p><p>Scoped components usually have their lifecycle tied to some screen or group of screens, and they have to be disposed of when those screens are finished. We could tie those components to the lifecycle of the activity\fragment. But when configuration changes occur, they are destroyed and recreated, so we have to store components across configuration changes. Besides, as we need to have an instance of a parent component to create child components, we also need some mechanism to find parent components.</p><p>In this blog post, we will take a look at how to store dagger components in Activity\Fragment and how to access a parent component to create child components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0a8cLiAOD9VkwBmauRcPQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/photo/bazaar-bottles-business-ceramic-15964/">Kokil Sharma</a></figcaption></figure><h3>Let’s imagine how our final result should look like</h3><p>We can utilize kotlin property delegates to create very concise code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/077aa3d17855b4b7b6e52e5183e91f2b/href">https://medium.com/media/077aa3d17855b4b7b6e52e5183e91f2b/href</a></iframe><p>This delegate should evaluate lambda and store the result for as long as Activity\Fragment lives, including configuration changes. If you following AndroidX releases, you can notice that this delegate looks very similar to the <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:fragment/fragment-ktx/src/main/java/androidx/fragment/app/FragmentViewModelLazy.kt?q=Fragment.viewModels">Fragment.viewModels</a> extension from fragment-ktx. However, we won’t be using fragment-ktx and will implement the delegate ourselves. But before we start, let’s dive into the history of retaining configuration changes in android.</p><h3>Retaining component across configuration changes</h3><p>We need to retain dagger component instance somehow when configuration changes, so that it has the same lifespan as Activity\Fragment, and would be automatically disposed of when Activity\Fragment destroys.</p><p>What we trying to achieve was traditionally done with the help of Activity.onRetainNonConfigurationInstance():</p><blockquote>Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration. You can return any object you like here, […], which can later be retrieved by calling getLastNonConfigurationInstance() in the new activity instance.</blockquote><p>Later, with Fragment API introduction in Android Honeycomb documentation was updated:</p><blockquote>If you are targeting Build.VERSION_CODES.HONEYCOMB or later, consider instead using a Fragment with Fragment.setRetainInstance(boolean).</blockquote><p>After that, when Andoridx became a thing, the recommendation changed again. As per androidx.activity version 1.0.0 release notes:</p><blockquote>The onRetainCustomNonConfigurationInstance() and the related getLastCustomNonConfigurationInstance() APIs have been deprecated. It is strongly recommended to use ViewModels to store non-configuration state as they offer a composable solution suitable for any ViewModelStoreOwner that makes the ownership of the retained objects clear and provides an onCleared() callback for cleaning up resources when the activity is finally destroyed.</blockquote><p>So now it is recommended to store non-configuration objects in ViewModels. As an added benefit, ViewModelStoreOwner is implemented by both Activity and Fragment, and any entity with a clear lifecycle can implement this interface as well (for example, ViewModelStoreOwner can be obtained for Navigation Component’s NavGraph).</p><h3>Creating a scoped component holder</h3><p>So it is clear that we need to use ViewModels to store our scoped dagger components. We have two options to choose from:</p><ol><li>Let every dagger component extend ViewModel, or</li><li>Store the component inside special ViewModel</li></ol><p>First is simple to implement, but pollutes component code, and forces it to be abstract class instead of an interface. The second option is better but has a constraint, that only one instance of a component can be stored in one ViewModelStore. We will stick with the second option, but you can choose first if it suits you more. So let’s define simple ViewModel, that holds our component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fd0096d0c44481152af07284c6485b/href">https://medium.com/media/28fd0096d0c44481152af07284c6485b/href</a></iframe><h3>Implementing the delegate</h3><p>Now we are ready to implement the delegate. First of all, to create an instance of our ScopedComponentHolder, we need to define ViewModelProvider.Factory. We can simply ignore the class parameter because we will always be creating ScopedComponentHolder in our ViewModelProvider:</p><pre>fun scopedComponent(componentProvider: () -&gt; T) {<br>    val viewModelFactory = object : ViewModelProvider.Factory {<br>        override fun &lt;VM : ViewModel&gt; create(klass: Class&lt;VM&gt;): VM {<br>            return ScopedComponentHolder(componentProvider()) as VM<br>        }<br>    }<br>    ...</pre><p>Now we can create ViewModelProvider to retrieve the instance of ScopedComponentHolder, that holds our component. If it was created before, its instance will be returned immediately, otherwise viewModelFactory will be used to create a new instance:</p><pre>val viewModels = ViewModelProvider(storeOwner, viewModelFactory)<br>val holder = viewModels.get(ScopedComponentHolder::class.<em>java</em>)<br>return holder.component as T</pre><p>Now we put it all together and define our delegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/035005186044d896384c1ba1789c138c/href">https://medium.com/media/035005186044d896384c1ba1789c138c/href</a></iframe><p>We simply wrap ViewModel access into Lazy property delegate, while also caching the result for further invocations, and declare our scopedComponent function.</p><p>With this delegate our component can be scoped to any Activity, Fragment or navigation graph from Navigation Component (from 2.2.0-alpha02 and above), all of which implement ViewModelStoreOwner.</p><h3>Finding parent component</h3><p>For child scope to be opened we need an instance of the parent component. But how do we get that instance? One way of solving this problem is to use <a href="https://gist.github.com/aasitnikov/d3bbaefc59ed399ea5c0e1d77d95f12a">ComponentFinder</a>. Similar to the <a href="https://github.com/google/dagger/blob/master/java/dagger/android/AndroidInjection.java">AndroidInjection</a> class, it first traverses parent fragments, then activity, and lastly application in search of a given interface. For ComponentFinder to work, we need to define an interface that returns the instance of dagger component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2eb5c6c3518ff584139eaf00750ccf/href">https://medium.com/media/6b2eb5c6c3518ff584139eaf00750ccf/href</a></iframe><p>Optionally we can define a special component finder object for convenience. It simply delegates to ComponentFinder, but can also define custom logic for finding a particular component. After that, any child fragment can use it to get the instance of the parent component. This is how it will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a7ac208da6613c0dc67d96094def59/href">https://medium.com/media/30a7ac208da6613c0dc67d96094def59/href</a></iframe><p>Note that ChildFragment have to be added either directly to ParentFragment.childFragmentManager or further down the hierarchy of child FragmentManagers. Also, note that inject() should be called before super.onCreate() — it is recommended because child fragments are created during this call.</p><p>To see how both scopedComponent and ComponentFinder work in an app you can check out this <a href="https://github.com/asitnkova/DaggerScopesSampleApp">sample</a>.</p><h3>Conclusion</h3><p>We created the property delegate that lets us store instances of dagger components in ViewModelStore, retaining them across configuration changes. The only limitation is that one instance of Activity\Fragment can only have one associated dagger component instance. As an alternative, you can replace the ScopedComponentHolder.component field with a Map, or make your dagger components extend ViewModel, as described in this <a href="https://proandroiddev.com/scoping-dagger-components-with-viewmodels-bcb23c68dbc3">blog post</a>.</p><h4>TL;DR</h4><ul><li>Store scoped dagger components in ViewModelStore.</li><li>Use AndroidInjection-like parent scope search algorithm to initialize child scope.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3e86a5e957" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/how-to-store-scoped-dagger-components-in-android-applications-4f3e86a5e957">How to store scoped Dagger Components in Android applications</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>
    </channel>
</rss>