<?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 Nimrod Dayan on Medium]]></title>
        <description><![CDATA[Stories by Nimrod Dayan on Medium]]></description>
        <link>https://medium.com/@nimroddayan?source=rss-49d94df33780------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CP4ZbMxsJyaLKQ6W7B6XoA.jpeg</url>
            <title>Stories by Nimrod Dayan on Medium</title>
            <link>https://medium.com/@nimroddayan?source=rss-49d94df33780------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:26:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nimroddayan/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[Rewriting a Complex Screen with Epoxy and Unidirectional Data Flow]]></title>
            <link>https://proandroiddev.com/rewriting-a-complex-screen-with-epoxy-and-unidirectional-data-flow-cd162919ac74?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd162919ac74</guid>
            <category><![CDATA[android-mvvm]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 05:09:13 GMT</pubDate>
            <atom:updated>2020-04-23T05:09:13.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*QHCKLhVtroDuNB5x8DGAFA.png" /></figure><p>One of the projects I was working on recently, which was among the first activity recording apps, had a very complex screen with a lot of user interaction and data (referred to as <em>Workout Summary</em> <em>Screen</em> from now on). Naturally, as you’d expect, it had legacy code and tech, which was a blocker for extending it with new features. A decision was made to rewrite this screen so that it can be easily extended with new features and also get rid of weird bugs.</p><p>In this article, I’ll go through how I rewrote it, the technology and architecture I picked for the task and why.</p><h3>Analyzing and Planning</h3><p>Before we jump to code, it’s important to understand what is the challenge, what we want to achieve and how we’d solve it.</p><h4>Screen overview</h4><p>As you can see in the cover image screenshot, the screen is fairly complex. There’s a RecyclerView with many different types of items. There are actually a lot more items when you scroll down, which aren’t shown in the screenshot.</p><p>We also have many interactable UI widgets, such as the like button, add a comment, pictures pager and others which affect the screen state. For instance, when the user clicks the like button, the like counter needs to be incremented or when the user adds a comment, that comment needs to be added to the screen.</p><h4>Deciding the technology and architecture</h4><p>The technology and architecture I picked for the task is a Unidirectional Data Flow powered by Jetpack ViewModel combined with <a href="https://kotlinlang.org/docs/reference/coroutines/flow.html">Kotlin Flow</a> and AirBnB’s <a href="https://github.com/airbnb/epoxy">Epoxy library</a> and its Kotlin extension functions, which provide the ability to write declarative UI.</p><p>Combining the above for this screen makes sense since this screen doesn’t only show data, but also responds to user input, which means this screen has multiple states. By modelling the UI states into state objects that encapsulate the data and combining it with Epoxy, which handles diffing of data out-of-the-box and dispatching UI changes respectively, we get Reactive UI.</p><p>The goal is that only the UI widgets that need to be updated will be updated without affecting other UI widgets. Data flows in one direction only and is immutable. It can only be changed in one place by copying the old state and changing it.</p><h3>Implementation</h3><h4>Modelling the UI state in Kotlin data classes</h4><p>A typical UI goes through 3 common states: Loading, Loaded and Error.</p><ul><li><strong><em>Loading</em></strong> is when data is loaded from disk or server. It can also be when we’re computing something.</li><li><strong><em>Loaded</em></strong><em> </em>is when the previous state (<em>Loading</em>) has finished successfully and now we have the result.</li><li><strong><em>Error</em></strong><em> </em>is when <em>Loading</em> state has failed and we want to show an error to the user.</li></ul><p>Utilizing Kotlin’s power, we can make use of <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">Sealed Classes</a> like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac67e7901842e555513aec17fec1c27/href">https://medium.com/media/4ac67e7901842e555513aec17fec1c27/href</a></iframe><blockquote>You might be wondering why do we need to have data property for <strong>Loading</strong> and <strong>Error</strong> states. This will become clearer soon.</blockquote><p>The next step is to model the UI to a Kotlin data class by walking through each RecyclerView item one by one from top to bottom and model a data class for it. Note that for simplicity, we will ignore the AppBar in this article and concentrate only on the RecyclerView.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb4f491a69f58181d21f4a4a6e016e74/href">https://medium.com/media/bb4f491a69f58181d21f4a4a6e016e74/href</a></iframe><p>We introduced a container class called WorkoutSummaryViewState, which holds references to the actual data that we’re going to present in the UI. Each *Item class is wrapped with ViewState sealed class we created earlier. You’ll shortly see the benefits of doing that.</p><h4>Implementing the ViewModel</h4><p>In this section, we’re going to use <a href="https://developer.android.com/jetpack">Google Jetpack</a> ViewModel. The advantage is that ViewModel instance is persisted throughout configuration changes.</p><p><strong>How does it work?</strong><br>We expose one LiveData property in the ViewModel, which the Activity/Fragment will observe. This LiveData will emit a new instance of WorkoutSummaryViewState everytime there’s a state change in the UI. To start the loading of data, we will also expose a function that will be called by the Activity/Fragment.</p><p><strong>Now here is the key in this architecture</strong>: Utilizing Kotlin Coroutines, we can load each item class in parallel and since each item has 3 states, we can use it to update the UI accordingly as data comes in. What we will get is lightning fast UI loads. Here is how it goes:</p><ol><li>Each item is loaded by a dedicated function call that returns a Kotlin Flow.</li><li>In our ViewModel entry point function, the one that is called from Activity/Fragment, we use Kotlin’s combine function to combine all the Flows together.</li><li>Due to the nature of combine function, we can make each Flow emit immediately with an initial state so that the combine function will emit a new value everytime one of the Flows emits a new Item state.</li><li>We then pass the combined result to the LiveData that is observed by the Activity/Fragment. (Example below).</li><li>Thanks to Epoxy’s diffing powers, this will result in flawless UI transitions and animations — no flickerings!</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8a41bf718c27fb2884880f043024bae/href">https://medium.com/media/b8a41bf718c27fb2884880f043024bae/href</a></iframe><p>For brevity, I included only the code for loading the likes in the snippet above. Let’s analyze it:</p><ol><li>Each Item has it’s own load function that launches a new coroutine and immediately returns with a Flow.</li><li>The Flow is actually a ConflatedBroadcastChannel, which keeps the last emitted item.</li><li>As the new coroutine starts, it emits the initial state right away with a Loading state.</li><li>Once all the functions in the combine function emit their initial state, the lambda in the combine function is invoked and right afterwards onEach function is invoked, which will emit a new instance of WorkoutSummaryViewState via the LiveData.</li><li>Each coroutine is still running, loading its data and once it finishes, it emits a new state via the channel of that Item — LikesItem in the code snippet above in a Loaded state.</li><li>In case of an error, we emit an Error state via the item specific channel.</li></ol><p><strong>What happens when a user hits the like button?</strong></p><ol><li>We launch a new coroutine that gets the old state from the item specific channel.</li><li>We update the database and reload the likes from the database while passing the previous state as the initial state for loadLikesItem() function. Why is it useful to pass the old state? If you recall, loadLikesItem() will immediately emit an initial state. By default, it is an empty state. To avoid clearing the item from the screen, we pass the old state. This can, of course, be improved if desired.</li><li>In case of an error, we follow the pattern, we emit an Error state and the previous state.</li></ol><blockquote>Notice that we always emit a new instance. This way our state is immutable and cannot be changed anywhere else.</blockquote><h4>Implementing the Activity and Epoxy Controller</h4><p>The next and final step is to implement the Activity and Epoxy Controller. The Activity is very basic. It gets an ID for which it needs to load data via Intent extras and calls the loadData(id) function. It subscribes to the LiveData that the ViewModel exposes and awaits for state emissions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42b1e6da64a2c3389b902d1539d2ebc5/href">https://medium.com/media/42b1e6da64a2c3389b902d1539d2ebc5/href</a></iframe><p>Now for the fun part, Epoxy controller and declarative UI 😃</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acacd7b2ce2b68d468355b0d7292d957/href">https://medium.com/media/acacd7b2ce2b68d468355b0d7292d957/href</a></iframe><p>In the Epoxy controller, we get the view state instance and we add the item (or Model in Epoxy terms) accordingly. Since we have the knowledge of what state each item is in, we can show individual loading indicators and error messages. Epoxy internally takes care to diff the new state with the old state and it will dispatch a notification to RecyclerView only if it found a difference.</p><blockquote>Note that unless specified otherwise, when using TypedEpoxyController, Epoxy will build the models and do the diffing on the main thread by default. That’s why we explicitly specify the Handlers in TypedEpoxyController&#39;s constructor (lines 2–3). EpoxyAsyncUtil class comes out-of-the-box with Epoxy. You can read more about this <a href="https://github.com/airbnb/epoxy/wiki/Epoxy-Controller#asynchronous-support">here</a>.</blockquote><p>And here’s what we achieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*a4tAY3Pm6g_ArZG06ps39g.gif" /><figcaption>The final result for likes</figcaption></figure><p>Not implemented this article, but implemented in the real app, adding a comment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6GZaspGSV3U4zlrRe1abLQ.gif" /><figcaption>Adding comments with the architecture presented in this article</figcaption></figure><p>If you liked this article, please remember to clap and follow me here on Medium and on Twitter for more articles in the future.</p><p><a href="https://twitter.com/nimroddayan"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd162919ac74" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/rewriting-a-complex-screen-with-epoxy-and-unidirectional-data-flow-cd162919ac74">Rewriting a Complex Screen with Epoxy and Unidirectional Data Flow</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[Expandable RecyclerView with Epoxy]]></title>
            <link>https://proandroiddev.com/expandable-recyclerview-with-epoxy-100515f5d026?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/100515f5d026</guid>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[ux-design]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Sat, 08 Jun 2019 08:01:02 GMT</pubDate>
            <atom:updated>2019-06-08T12:22:35.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-llMH2KN1zdVJ2BEhCq2w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@republica?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adam Śmigielski</a> on <a href="https://unsplash.com/search/photos/feature?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://github.com/airbnb/epoxy">Epoxy</a>, an Android library developed by Airbnb, is a widely known and used library for building complex screens in a RecyclerView.</p><p>It has built-in support for async diffing (using DiffUtil) and promotes immutability while enforcing best practices when working with RecyclerView.</p><p>In this article, I’m going to show you how you could build a list with expandable items, a.k.a. accordion, using Epoxy — assuming you’re already familiar with the library.</p><p>We’re going to build a list of video game titles grouped into genres.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HyXudShP0dFEBQ-3MNf2Kg.gif" /></figure><h3>Preparing the Models</h3><p>Epoxy provides various ways to generate the Epoxy models. The code in this article is written in Kotlin and since I’m fond of Data Binding, I will use <a href="https://github.com/airbnb/epoxy/wiki/Data-Binding-Support">Epoxy with Data Binding</a> model generation from XML layouts. Each layout is prefixed with viewholder_ and I have the following configuration in package-info.java:</p><pre>@EpoxyDataBindingPattern(rClass=R.class, layoutPrefix=“viewholder”)</pre><pre>package com.nimroddayan.epoxysample;</pre><pre>import com.airbnb.epoxy.EpoxyDataBindingPattern;</pre><p>To get this to work, you have to include the following dependencies in build.gradle:</p><pre>implementation “com.airbnb.android:epoxy:$epoxyVersion”<br>implementation “com.airbnb.android:epoxy-databinding:$epoxyVersion”<br>kapt “com.airbnb.android:epoxy-processor:$epoxyVersion”</pre><h4><strong>Header model</strong></h4><p>We’ll first create the genre item, which I like to refer to as the “header” item:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e932793146704baba45917ad21d00534/href">https://medium.com/media/e932793146704baba45917ad21d00534/href</a></iframe><p>We have 2 data binding variables:</p><ul><li>genre — is a data class that holds info about genre</li><li>onHeaderExpanded — is a standard Android onClick listener</li></ul><blockquote>Notice that you have to use Android’s own View.OnClickListener instead of a custom interface or Kotlin lambda so that Epoxy will ignore it when it does the diffing.</blockquote><p>That’s all for the header. Let’s proceed to the items.</p><h4><strong>Item model</strong></h4><p>This model will represent a single game title.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604f42d4af6f496345d17fa3cb74f390/href">https://medium.com/media/604f42d4af6f496345d17fa3cb74f390/href</a></iframe><h3><strong>Creating the View Entities</strong></h3><p>Now we’ll create the view entities that will be passed to the Epoxy controller for building the models.</p><p>Create a Kotlin file with the following data classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/169fcb8cdf25b2767a1b7b260b63d9ae/href">https://medium.com/media/169fcb8cdf25b2767a1b7b260b63d9ae/href</a></iframe><p>We have a global ID generator here to make sure that each object gets a unique ID. We’ll see soon how it’s used.</p><p>Next, we’ll move to the Epoxy controller</p><h3><strong>Epoxy Controller</strong></h3><p>This is where the magic happens. Taking a closer look at Genre class, we see that we have a property isExpanded which is false by default.</p><p>We’ll use this property to tell Epoxy whether to add models for the games under this genre or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/339431f37e76239dbaecaf90a64ba59d/href">https://medium.com/media/339431f37e76239dbaecaf90a64ba59d/href</a></iframe><p>When the genre (header) is clicked, the onClick listener that we wired up in XML will be invoked — passing along the Epoxy model that was associated to it. We get the Genre instance from the model and pass it to the listener that we defined in the container. We’ll see soon how we handle it in the ViewModel.</p><p>Expand &amp; Collapse animations come for free due to DiffUtil dispatching the right notifications to the adapter.</p><blockquote>Note that having unique identifiers per each model is key to proper diffing. Epoxy compares the old and new models by their IDs and content.</blockquote><h3><strong>Creating the View Entities</strong></h3><p>We’ll use a ViewModel to create our view entities and also to handle the expanded event when the user clicks the genres.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ce0f63fdb821e0e6441d8e6b585bf83/href">https://medium.com/media/6ce0f63fdb821e0e6441d8e6b585bf83/href</a></iframe><p>GamesListViewModel emits a new Container, which holds the data we need to show in the list, via a LiveData once it’s initialized . This is where you’d normally query the database or make a network call to fetch your data.</p><p>The interesting part is the implementation of OnGenreExpanded. Here’s a breakdown of the code:</p><ol><li>Since we emit a new Container instance on initialization via a LiveData, we can get the previous Container instance via _liveData.value property. Alternatively, you can also pass the container object to OnGenreExpanded.</li><li>We then map all the genres and by doing so we actually create a new genre list.</li><li>Next, we compare the ID of the Genre instance that was passed to the event to IDs of each genre in the list.</li><li>Once we find a match, we make copies of the genre and flip its isExpanded flag.</li><li>After we’re finished mapping, we end up with a copy list that has only one genre’s isExpanded set. Lastly, we make copy of the entire container and plug the new genres list we just created into it .</li></ol><blockquote>It might seem inefficient to make copies of the objects instead of just modifying them directly, but immutability is key for bug free code. When dealing with multiple threads, in cases such as, loading data from a database or fetching it from the network, it’s better to avoid concurrent access to mutable state.</blockquote><p>We’re done with the ViewModel, now let’s plug it into an Activity and launch the app.</p><h3><strong>Putting it All Together</strong></h3><p>Finally, we connect all the pieces together. Create a new Activity called GamesListActivity with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d61fcd336b832188c4f4e0f3719959b/href">https://medium.com/media/7d61fcd336b832188c4f4e0f3719959b/href</a></iframe><p>We observe gamesLiveData from the GamesListViewModel and every time a new container is emitted, we simply forward it to the Epoxy controller.</p><p>And the layout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6e8da1f467ef0aa979fc62c7c12bc4f/href">https://medium.com/media/b6e8da1f467ef0aa979fc62c7c12bc4f/href</a></iframe><p>You can now run the app and see it in action!</p><p>If you liked this article, please remember to clap and follow me here on Medium and on Twitter for more articles in the future.</p><p><a href="https://twitter.com/nimroddayan"></a></p><p><em>Special thanks to </em><a href="https://medium.com/u/f2c5d7f27a10"><em>Mikko-Ville Salo</em></a><em> for guiding me on this topic.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=100515f5d026" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/expandable-recyclerview-with-epoxy-100515f5d026">Expandable RecyclerView with Epoxy</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[Saving UI state with ViewModel SavedState and Dagger]]></title>
            <link>https://proandroiddev.com/saving-ui-state-with-viewmodel-savedstate-and-dagger-f77bcaeb8b08?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/f77bcaeb8b08</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 17:01:00 GMT</pubDate>
            <atom:updated>2020-06-19T19:48:39.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixBILv0Ox0ht6ktGXn-jdw.png" /></figure><blockquote>Updated Dagger integration to recommend using Dagger <a href="https://developer.android.com/training/dependency-injection/hilt-android">Hilt: Dependency Injection</a>, which greatly simplifies dependency injection in ViewModels.</blockquote><blockquote>Updated to Lifecycle ViewModel SavedState version 2.2.0.<br>Check out my <a href="https://github.com/nimrodda/github-commit-browser">sample Github repository</a> for a complete working example of everything I discuss here.</blockquote><p><a href="https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate">Saved State module for ViewModel</a> is a new library from Google that builds on top of ViewModel architecture component. It let&#39;s you restore the UI state after a process stop.</p><p>In this article, I&#39;m going to walk you through the basic usage of this library and continue deeper into a more advanced use case of integrating it with Dagger:</p><ul><li><a href="#6acf">Saving UI State</a> — The Challenge</li><li><a href="#f2a2">Introduction to Saved State module for ViewModel</a></li><li><a href="#379a">SavedState ViewModel with additional constructor arguments</a></li><li><a href="#7f89">Integrating SavedState ViewModel with Dagger</a> and Hilt</li><li><a href="#73d2">Dagger Assisted Inject</a></li></ul><h3>Saving UI State — The Challenge</h3><p>One of the main challenges in Android development is persisting the state of the Activity/Fragment when a configuration change occurs. Android Architecture Components features the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">ViewModel component</a> to address this.</p><p>Nevertheless, a configuration change is not the only behavior that results in Activity/Fragment losing its state. The state can be lost also when the system runs out of resources and has to stop the app’s process while it’s in the background. The easiest way to reproduce such behavior is to enabled <em>Don’t Keep Activities</em> in <em>Developer Options</em> of your test device. By doing so, the Activity will be destroyed whenever you leave it. ViewModels alone do not cover this case and there’s a <a href="https://medium.com/androiddevelopers/viewmodels-persistence-onsaveinstancestate-restoring-ui-state-and-loaders-fc7cc4a6c090">very good article about this</a> by <a href="https://medium.com/u/fdba971ca390">Lyla Fujiwara</a>, which I encourage you to read.</p><p>To summarize Lyla’s article, the only way to address this case is by overriding onSaveInstanceState(Bundle) in the Activity/Fragment and persist the state in the passed Bundle. If what you want to persist is in the ViewModel, this requires communication between ViewModel and Activity/Fragment. One way would be to introduce getInstanceState(): Map&lt;String, Object&gt; and setInstanceState(state: Map&lt;String, Object&gt;) in the ViewModel for setting and getting the state to/from the ViewModel when the Activity is destroyed/recreated. A major drawback of this approach is that now the state of the ViewModel is deferred to specific lifecycle events.</p><blockquote>Note that you shouldn’t use this method for persisting large objects (the limit is 1MB), but only the bare minimum required to reconstruct the UI to its previous state. Otherwise, you may encounter <a href="https://developer.android.com/reference/android/os/TransactionTooLargeException">TransactionTooLargeException</a>.</blockquote><h3>Introduction to Saved State module for ViewModel</h3><p>Google has released a new library called <a href="https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate">ViewModel SavedState</a>, which is an addition to ViewModel to support Activity/Fragment state persistence through process stop. The way it works is by passing a <a href="https://developer.android.com/reference/androidx/lifecycle/SavedStateHandle">SavedStateHandle</a> to the ViewModel’s constructor, which you can then use to restore/save the state.</p><p>We start by including the necessary Gradle dependencies and creating the ViewModel:</p><p>app/build.gradle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56531c4a4ea5649b7da11e1bb6ff2aab/href">https://medium.com/media/56531c4a4ea5649b7da11e1bb6ff2aab/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2691816116e307ef82b4a735bbf8df0b/href">https://medium.com/media/2691816116e307ef82b4a735bbf8df0b/href</a></iframe><p>handle: SavedStateHandle is just a map. You can query it for its content and store the state in it like you&#39;d normally do with a Bundle passed to onSaveInstanceState(). Note that to store complex objects, you have to implement the Parcelable interface.</p><blockquote><em>Pro Tip: Kotlin’s Android Extensions has a neat feature that implements the </em><em>Parcelable interface for you by annotating your data classes with </em><em>@Parcelize. Read more </em><a href="https://kotlinlang.org/docs/tutorials/android-plugin.html#parcelable"><em>here</em></a><em>.</em></blockquote><p>To get an instance of DetailViewModel in our Activity, we will use the new extension function viewModels included in androidx.activity:activity-ktx library, which returns a Lazy delegate to access the Activity’s ViewModel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b72c23e56097d190c241a730f46096d/href">https://medium.com/media/6b72c23e56097d190c241a730f46096d/href</a></iframe><h3>ViewModel with constructor arguments</h3><p>If you’re already using ViewModels in your project, chances are that you’re passing other arguments to the ViewModels’ constructors via your own custom ViewModelProvider.Factory so let’s see what are the options we have in this case.</p><p>SavedState module ships with an abstract factory called <a href="https://developer.android.com/reference/androidx/lifecycle/AbstractSavedStateVMFactory">AbstractSavedStateViewModelFactory</a>. This class requires us to pass an instance of <a href="https://developer.android.com/reference/androidx/savedstate/SavedStateRegistryOwner">SavedStateRegistryOwner</a> and nullable Bundle as the default state.</p><p>Let’s add another argument, githubApi, to the ViewModel’s constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7a4e586fbc04681a9e5bb4651104927/href">https://medium.com/media/a7a4e586fbc04681a9e5bb4651104927/href</a></iframe><p>The ViewModel above calls the Github API with the ID we stored previously in SavedStateHandle.</p><p>Once again, to get this ViewModel instance we will use viewModels extension function and pass an implementation of AbstractSavedStateViewModelFactory that knows how to construct this ViewModel and pass the required dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af41108e561b7824d3014b2180c7eca0/href">https://medium.com/media/af41108e561b7824d3014b2180c7eca0/href</a></iframe><p>And then hook it up to the Activity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b27a677fdf168a1af9935a10b86de115/href">https://medium.com/media/b27a677fdf168a1af9935a10b86de115/href</a></iframe><p>We’re passing a new instance of DetailViewModelFactory to viewModels extension function. The factory takes an instance of GithubApi and SavedStateRegistryOwner instance as a 2nd argument, which is in this case, the Activity. This 2nd argument is very important since it ties the saved state to the current component (either Activity or Fragment). In case you’re creating a shared ViewModel among Fragments, you should pass the host Activity instance here and use activityViewModels extension function instead of viewModels.</p><blockquote>Note that a factory is needed for each ViewModel that takes SavedStateHandle as a constructor argument.</blockquote><h3>Integrating SavedState ViewModel with Dagger and Hilt</h3><blockquote>This section talks about how to inject ViewModel factories with Dagger, which results in <strong>a lot of boilerplate code</strong> that can be completely avoided by using Dagger <a href="https://developer.android.com/training/dependency-injection/hilt-android">Hilt: Dependency Injection</a> for Android built on Dagger to replace Dagger Android. When using Hilt, you won’t need any ViewModel factories anymore since that’s already being taken care of by Hilt. Please refer to the <a href="https://developer.android.com/training/dependency-injection/hilt-jetpack">official guide</a> on how to add this support. Note that you must already be using Hilt. If you’re still using plain Dagger or Dagger Android and curious to see what I mean, <a href="https://github.com/Nimrodda/github-commit-browser/pull/5">check out this PR</a> that migrated from Dagger Android to Hilt. You’d be amazed how much code has been removed.</blockquote><p>The traditional ViewModel factory with Dagger looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c6af6281b501456697b889290e4c71/href">https://medium.com/media/a5c6af6281b501456697b889290e4c71/href</a></iframe><p>In the code snippet above, we have a ViewModelProvider.Factory implementation that is injected with a map of ViewModel class types and their Providers, which will then create a new instance of the required ViewModel by calling Provider.get() with all the dependencies injected to the ViewModel’s constructor.</p><p>Next, we utilize <a href="https://google.github.io/dagger/multibindings.html">Dagger’s MultiBinding</a> feature to construct the map by binding each ViewModel class type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fdd87a516e828f459b3da03e679fc3c/href">https://medium.com/media/7fdd87a516e828f459b3da03e679fc3c/href</a></iframe><p>As you can see in the following code snippet, we now annotated DetailViewModel&#39;s constructor with @Inject so that dagger will perform constructor injection and supply the dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/920b80146967e6a666c329ed28d17e34/href">https://medium.com/media/920b80146967e6a666c329ed28d17e34/href</a></iframe><p>You may have noticed that we have a problem now.</p><ul><li>First, we need to extend AbstractSavedStateViewModelFactory and not ViewModelProvider.Factory</li><li>and second, the we have a new ViewModel constructor argument, SavedStateHandle, but we only get its instance when AbstractSavedStateViewModelFactory calls our implementation of create() function where it then passes the SavedStateHandle instance. With the traditional Dagger setup, we get the ViewModel instance from Provider&lt;ViewModel&gt;.get() and there’s no option to pass extra constructor parameters so this approach with Dagger is not going to work anymore. We’ve already seen earlier that the only way to solve this problem is by having a ViewModel specific factory.</li><li>Moreover, AbstractSavedStateViewModelFactory takes SavedStateRegistryOwner, which if you recall, is a very important argument that associates the saved state to the Activity/Fragment. We cannot just inject whatever Activity/Fragment instance here.</li></ul><p>Unfortunately, the traditional approach is no longer valid when using SavedState ViewModel. As mentioned previously, you have to create one Factory per ViewModel while making sure that you pass the right SavedStateRegistryOwner instance.</p><p>Nevertheless, we can still use Dagger to inject other dependencies needed for the ViewModel by creating 2 layers of factories — covered in the next section.</p><h4>Injectable factory per ViewModel</h4><p>Create an interface that each ViewModel factory will need to implement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f544a848d3b4e71e7dbb018296be6b2/href">https://medium.com/media/4f544a848d3b4e71e7dbb018296be6b2/href</a></iframe><p>Now create a factory per each ViewModel and implement the interface. Make sure to make this factory injectable so that Dagger will inject all the dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3cc8680219a5419e42ff4aedd90addc/href">https://medium.com/media/f3cc8680219a5419e42ff4aedd90addc/href</a></iframe><blockquote>Notice that we don’t annotate the ViewModel constructor with @Inject since we the factory will create it.</blockquote><h4>Implementing AbstractSavedStateViewModelFactory for handling multiple ViewModels</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a80c6109895550deed810a03e5533c/href">https://medium.com/media/b1a80c6109895550deed810a03e5533c/href</a></iframe><p>With the above generic implementation, the factory can create any ViewModel since it takes the factory interface we created earlier.</p><p>Now we hook it up to the Activity by first injecting the ViewModel factory and then using viewModels extension function while passing AbstractSavedStateViewModelFactory implementation, which takes the specific ViewModel factory and the current Activity instance as a SavedStateRegistryOwner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2da897567bd98521510b19dce9b92de1/href">https://medium.com/media/2da897567bd98521510b19dce9b92de1/href</a></iframe><p>Check out my <a href="https://github.com/nimrodda/github-commit-browser">sample Github repository</a> for a complete working example of everything I discussed here. Note that master branch of this repository has already migrated to Hilt. In case you’d like to inspect the code prior to the migration, <a href="https://github.com/Nimrodda/github-commit-browser/tree/savedstate-factories">please check out this branch instead</a>. If you liked this article, please remember to clap and follow me here on Medium and on Twitter for more articles in the future.</p><blockquote><strong><em>⚠️</em>UPDATE v2.2.0</strong>: The article ends here. The next section was written when the library was in alpha stage and is outdated. It talks about Assisted Inject library for Dagger, which I don’t recommend to use anymore with SavedState ViewModels for the reasons I listed earlier — mainly because it’s very tricky to control what instance of SavedStateRegistryOwner is injected by Dagger or even impossible to inject at all if you’re using FragmentFactory due to cyclic dependency, so I just recommend to completely avoid it unless you’re an adventurer <em>😄</em></blockquote><h3>Helping Dagger Help You</h3><blockquote><em>This subtitle was adopted from </em><a href="https://medium.com/u/8ddd94878165"><em>Jake Wharton</em></a><em>’s</em> <em>talk</em> <a href="https://jakewharton.com/helping-dagger-help-you/">Helping Dagger Help You</a> <em>about</em> <em>Dagger Assisted Inject</em> <em>at DroidCon UK.</em></blockquote><blockquote>IMPORTANT: THIS SECTION IS OUTDATED AND IS NOT RECOMMENDED ANYMORE!</blockquote><p>We need to <em>assist</em> Dagger to construct the ViewModel by passing the instance of SavedStateHandle we get from AbstractSavedStateVMFactory.create(). To do that, we’ll use <a href="https://github.com/square/AssistedInject">AssistedInject</a> as an add-on library to Dagger. AssistedInject generates factories which we can then use to construct a map of ViewModel types and their factories by utilizing Dagger’s MultiBinding feature as we’ve done before.</p><p>First, let’s include the Gradle dependencies:</p><p>app/build.gradle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4c004d747f269dfa5969cc3164ed3e3/href">https://medium.com/media/b4c004d747f269dfa5969cc3164ed3e3/href</a></iframe><p>With AssistedInject we can tell Dagger which constructor argument we want to assist with by annotating the argument with @Assisted annotation and instead of using @Inject, to inject the ViewModel, we will use @AssistedInject.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95998e53220bbc20a9440be5111c58f7/href">https://medium.com/media/95998e53220bbc20a9440be5111c58f7/href</a></iframe><p>The next step is to make AssistedInject generate the factory for this ViewModel. We need to create a factory interface that takes the argument(s) that we want to assist with and returns an instance of the ViewModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f544a848d3b4e71e7dbb018296be6b2/href">https://medium.com/media/4f544a848d3b4e71e7dbb018296be6b2/href</a></iframe><p>Since we want to support many different types of ViewModel factories, we create a generic factory interface as shown above. We then extend this interface per ViewModel and return the type of the ViewModel we want to return:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf92b6c9c6593e98fb704a23e8d52f9/href">https://medium.com/media/ecf92b6c9c6593e98fb704a23e8d52f9/href</a></iframe><blockquote>Note that the factory interface above must be nested inside the ViewModel class otherwise you will get a compilation error.</blockquote><p>If we build our project now, we will have a factory named DetailViewModel_AssistedFactory generated for our ViewModel. Next we will need to get these generated factories into our dependency graph. AssistedInject can generate a Dagger module for us so we can then just include it in one place:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3162354baf61bed918cf6aaf9e3cd01f/href">https://medium.com/media/3162354baf61bed918cf6aaf9e3cd01f/href</a></iframe><p>We create an empty Dagger module and annotate it with @AssistedModule. We then build to get the factories module, AssistedInject_ViewModelAssistedFactoriesModule, generated and include it in Module(includes = [..]) as shown above. Now, include this module in your ApplicationComponent modules so that it’s visible everywhere in the graph.</p><p>The next step is to modify our binding to construct a map of ViewModel types and their factories:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e89545a1b05f7ef8bab1631504a4f11/href">https://medium.com/media/9e89545a1b05f7ef8bab1631504a4f11/href</a></iframe><blockquote><em>Notice that previously we were binding the </em><em>ViewModels directly to the map, but now we’re binding the ViewModel factories instead into the map.</em></blockquote><p>If you recall from DetailViewModelFactory, we have a constructor that takes two arguments: SavedStateRegistryOwnerand a nullable Bundle. We need to supplement our ViewModelFactory to take these two extra arguments in addition to a map of ViewModel types and their factories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c151ca4e56221a6f0121f5d14638617c/href">https://medium.com/media/c151ca4e56221a6f0121f5d14638617c/href</a></iframe><p>As we can see in the code snippet above, our injected map now holds ViewModelAssistedFactory&lt;out ViewModel&gt;&gt;ies instead of Provider so that we can now call create() and pass the SavedStateHandle to the factory viewModelMap[modelClass]?.create(handle).</p><p>Dagger needs to know how to inject the two new arguments (SavedStateRegistryOwner and a nullable Bundle) so let’s set up the bindings for them as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c6f574e7a76996b066b0766e2848155/href">https://medium.com/media/0c6f574e7a76996b066b0766e2848155/href</a></iframe><blockquote><em>The snippet above is intentionally written in Java due to the added static provide method. I prefer writing Dagger modules in Java instead of having a nested </em><em>@Module annotated companion object.</em></blockquote><p>The only thing left to do now is to inject ViewModelFactory in the Activity and get the ViewModel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7205faa66dbe2080468eb0b173ef2ed9/href">https://medium.com/media/7205faa66dbe2080468eb0b173ef2ed9/href</a></iframe><p>Finally, we inject ViewModelFactory to the Activity and pass its instance to viewModels extension function to get our ViewModel instance with all of its dependencies injected by Dagger via the assisted factory we created.</p><p>We now have a full working set up of SavedState, ViewModel and Dagger working together.</p><p>I’ve included a sample project, which demonstrates everything discussed in this article on <a href="https://github.com/Nimrodda/github-commit-browser.git">Github</a>.</p><p>If you liked this article, please remember to clap and follow me here on Medium and on Twitter for more articles in the future.</p><p><a href="https://twitter.com/nimroddayan"></a></p><p>References:</p><ul><li><a href="https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate">SavedState module for ViewModel</a></li><li><a href="https://developer.android.com/guide/components/activities/process-lifecycle">Processes and Application Lifecycle</a></li></ul><p>Special thanks to <a href="https://medium.com/u/8ddd94878165">Jake Wharton</a> for pointing me to AssistedInject.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f77bcaeb8b08" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/saving-ui-state-with-viewmodel-savedstate-and-dagger-f77bcaeb8b08">Saving UI state with ViewModel SavedState and Dagger</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[Gradually Migrate to Room — The Missing Guide]]></title>
            <link>https://medium.com/android-news/gradually-migrate-to-room-the-missing-guide-133520c7260?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/133520c7260</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[android-room]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Sun, 04 Nov 2018 14:24:56 GMT</pubDate>
            <atom:updated>2020-08-31T12:16:51.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*we1fau5voor1D9BHUsfzSw.jpeg" /></figure><h3>Gradually Migrate to Room While</h3><p>So you decided to migrate your data access layer to use Room, but the number of tables in your database along with how deeply integrated your DAO classes are in your codebase (whether you’re using another ORM library or not) freaks you out. Based on all the guides you’ve read so far, you know that to get into Room’s world, it’s either <strong>all</strong> or <strong>nothing</strong>, right? Well, not really. There’s a way to do it gradually while still releasing your app to public and slowly migrating one table at a time — having your old database (using outdated ORM) and Room co-exist.</p><h3>The Reality</h3><p>The tutorials that you’ve read so far were more suitable for small scale apps (or to be more accurate, sample apps presented on blogposts, which are far away from <em>real</em>-world apps with <em>real</em> users).</p><p>The project that I’m currently working on is several years old and has more than 20 tables. Being offline is one of its key features. There’re users with potentially years of data (synced also to the server, of course). The project is currently using ORMLite, which is tightly integrated across the codebase.</p><p>As you may already know, changing your database’s ORM requires migrating all database tables along with their DAO classes at once, since you can only have one SQLiteOpenHelper talking to one database at a time. This can be a huge task when you have more than 20 tables and DAO classes used all over the codebase. Not to mention that you also need to convince your business department, product owner and whatnot that this is a necessary thing to do in order to ease the development and maintenance in the long run.</p><blockquote>Some of the reasons why you can’t have more than one SQLiteOpenHelper for the same database include: <a href="https://touchlab.co/2011-10-single-sqlite-connection/">concurrency</a> — there can only be one connection to the database at given time, migrations and versioning — database migrations and versioning will only be executed on the firstly created SQLiteOpenHelper instance.</blockquote><h3>The Clone — Creating a new Room database</h3><p>If you’re in a big team, you’re most likely to continue releasing updates while this refactoring is on going. To keep up with this requirement, you’ll have to create a separate new database specifically for Room. You will then gradually create clone tables in this database, i.e. copy the data from the old tables to the new ones, and at the same time refactor your codebase to make use of the newly introduced Room DAO classes.</p><h3>Identify the Table to Migrate</h3><p>Your first step is to identify the table (or set of associated tables) that you’d like to migrate to Room. I suggest starting with one table, normally one that is utilized by one feature. Once you identified it, proceed to integrating Room by creating the necessary class for the database, the table and its DAO class. Room has a very good <a href="https://developer.android.com/training/data-storage/room/">training</a> guide and there’s also another <a href="https://medium.com/androiddevelopers/7-steps-to-room-27a5fe5f99b2">guide</a> by <a href="https://medium.com/u/d5885adb1ddf">Florina Muntenescu</a> that explains how to get started so I won’t repeat the steps to integrate Room here.</p><blockquote><strong>Pro-tip</strong>: make sure to configure Room to generate the JSON schema file (enabled by default). It will help you later unit testing your Room migrations when new tables are introduced in later versions. The generated JSON files contain the SQL statements that Room executes to create the tables. You will have to configure the location for the schema files and set the location as a source set for test configuration. It’s all explained <a href="https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema">here</a>.</blockquote><h3>Migrating the Data to Room</h3><p>Now that you have Room set up and your first Room Entity class (a.k.a. table), we will need to copy the data from the old database table to the new one. To do that, we will utilize migrations on the old database via SQLiteOpenHelper.onUpgrade() or the respective upgrade mechanism in the ORM library you’re currently using.</p><p>Let’s assume we have a pre-filled database called FeedDatabase that contains 2 tables, feed and comments with the following SQLiteOpenHelper implementation:</p><pre>class FeedDatabase(<br>    context: Context<br>) : SQLiteOpenHelper(context, DB_NAME, null, DB_VER) {<br>    override fun onCreate(db: SQLiteDatabase?) {<br>        db?.apply {<br>            execSQL(SQL_CREATE_FEED)<br>            execSQL(SQL_BOOTSTRAP_FEED)<br>            execSQL(SQL_CREATE_COMMENTS)<br>            execSQL(SQL_BOOTSTRAP_COMMENTS)<br>        }<br>    }<br><br>    override fun onUpgrade(<br>        db: SQLiteDatabase?, <br>        oldVersion: Int, <br>        newVersion: Int) {<br>    }<br>}</pre><p>Assuming we want to migrate comments table to Room, here are the steps we need to follow:</p><ol><li>We need to increment the old database’s version so that we can write a migration. Let’s assume the old database’s version is <em>2</em> after incrementing it.</li><li>Remove the SQL statements that creates comments table from FeedDatabase.onCreate().</li><li>Next, we’ll write the migration from the previous version (<em>1</em>) to the new version (<em>2</em>). What we need to do is query the old table and map each row in the Cursor to the Room Entity. In my case, this entity is called Comment. Each of these objects will then be added to a list, which will then be passed to the Room DAO class to be inserted into the new table.</li></ol><p>Here’s how this migration function looks like:</p><pre>fun upgrade(<br>    dbExecutor: Executor,<br>    db: SQLiteDatabase?,<br>    feedRoomDatabase: FeedRoomDatabase,<br>    oldVersion: Int,<br>    newVersion: Int<br>) {<br>    if (oldVersion == 1) {<br>        db?.apply {<br>            <em>// Query old table<br>            </em>query(Comment.TABLE_NAME).use { cursor -&gt;<br>                if (cursor.moveToFirst()) {<br>                    val comments = <em>mutableListOf</em>&lt;Comment&gt;()<br>                    do {<br>                        <em>// Map to entity and add to list<br>                        </em>comments.add(Comment.fromCursor(cursor))<br>                    } while (cursor.moveToNext())<br>                    <em>// Insert the list to the new table<br></em><strong><em>                    </em>dbExecutor.execute {<br>                        feedRoomDatabase.commentDao()<br>                            .insert(comments)<br>                    }<br></strong>                }<br>            }<br>            <em>// Finally, we drop the old table<br>            </em>execSQL(<em>SQL_DROP_COMMENTS</em>)<br>        }<br>    }<br>}</pre><blockquote>Notice that there’s a caveat here. If the app crashes during the migrations, we might end up in a state where the data was already copied to the new table. When this migration runs for the 2nd time, attempting to insert existing rows to the new table might result in a crash unless we specify that our conflict resolution strategy is to replace existing rows.</blockquote><blockquote>Another issue might occur if the migrations completed successfully, yet inserting the data to the new table has failed, which will result in the data never getting copied to the new table. In this case, you should hopefully be able to recover the data from the server during your period sync.</blockquote><p>CommentDao for reference:</p><pre>@Dao<br>interface CommentDao {<br>    @VisibleForTesting<br>    @Query(&quot;SELECT * FROM <strong>${</strong>Comment.TABLE_NAME<strong>}</strong>&quot;)<br>    fun testFetchAll(): List&lt;Comment&gt;<br><br>    @Insert(onConflict = <strong>OnConflictStrategy.<em>REPLACE</em></strong>)<br>    fun insert(comment: Comment)<br><br>    @Insert(onConflict = <strong>OnConflictStrategy.<em>REPLACE</em></strong>)<br>    fun insert(comments: List&lt;Comment&gt;)<br>}</pre><p>And here is how it looks when it’s hooked up to our SQLiteOpenHelper implementation:</p><pre>class FeedDatabase private constructor(<br>    private val dbExecutor: Executor,<br>    private val feedRoomDatabase: FeedRoomDatabase,<br>    context: Context<br>) : SQLiteOpenHelper(context, <em>OLD_DB_NAME</em>, null, <em>DB_VER</em>) {<br>    override fun onCreate(db: SQLiteDatabase?) {<br>        create(db)<br>    }<br><br>    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {<br>        upgrade(dbExecutor, db, feedRoomDatabase, oldVersion, newVersion)<br>    }<br><br>    companion object {<br>        @Volatile<br>        private var INSTANCE: FeedDatabase? = null<br><br>        fun getInstance(<br>            dbExecutor: Executor,<br>            feedRoomDatabase: FeedRoomDatabase,<br>            applicationContext: Context<br>        ): FeedDatabase {<br>            return INSTANCE ?: <em>synchronized</em>(this) {<br>                FeedDatabase.INSTANCE ?: FeedDatabase(dbExecutor, feedRoomDatabase, applicationContext).also {<br>                    FeedDatabase.INSTANCE = it<br>                }<br>            }<br>        }<br>    } // create() and upgrade() were omitted for brevity <br>}</pre><p>We’re passing the Room database instance to the old database constructor so we can then use it when we do the migration. Both create() and upgrade() methods are static, i.e. companion object methods, so that we can later call them from a unit test. create() method takes an optional version that defaults to the new database version, which we’ll then use from a unit test to create the database in a specific version.</p><pre>fun create(db: SQLiteDatabase?, version: Int = DB_VER) {<br>    db?.apply {<br>        <em>// Left for testing<br>        </em>if (version == 1) {<br>            execSQL(SQL_CREATE_COMMENTS)<br>            execSQL(SQL_BOOTSTRAP_COMMENTS)<br>        }<br><br>        execSQL(SQL_CREATE_FEED)<br>        execSQL(SQL_BOOTSTRAP_FEED)<br>    }<br>}</pre><h3>Assuring the Migration is Executed</h3><p>The migration will be executed only if we access the old database, e.g. either by callingFeedDatabase.readableDatabase or FeedDatabase.writableDatabase in this case. This means we will get an empty result when we query the data from the new table if the migration hasn’t been executed.</p><p>In the example below, I chose to call it on Application.onCreate():</p><pre>class App : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        val dbExecutor = Executors.newSingleThreadExecutor()</pre><pre>        <em>// By accessing the old database we make sure <br>        // that the migrations are executed<br>        </em>FeedDatabase.getInstance(dbExecutor,<br>         FeedRoomDatabase.getInstance(this), this).readableDatabase<br>    }<br>}</pre><p>We’re done with the migration. Our next step is to test that it actually works. Before we continue to testing, make sure to increment your app’s version code.</p><h3>Testing the Migration</h3><p>We need to test that the migration actually works. One way to test is to install a previous version of the app and then install the new version and see that the data is migrated to the new Room database. But, if you’re like me, you’d want to have a unit test to to cover it as well.</p><p>Room is very convenient to unit test, especially migrations. Here’s a <a href="https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975">very good guide</a> on how to unit test Room migrations. Nevertheless, in our case the migration is not done on the Room database, but instead it’s done on the old database SQLiteOpenHelper implementation. Unlike Room, the traditional SQLiteOpenHelper doesn’t include built-in API for testing migrations, but we can still do something very similar.</p><pre>@Test<br>fun migration1to2DataCopiedSuccessfullyToNewDatabase() {<br>    val newDb = Room.inMemoryDatabaseBuilder(<br>        appContext,<br>        FeedRoomDatabase::class.java)<br>        .build()<br><br>    <em>// Create old database in version 1 and then<br>    // apply migration to version 2<br>    </em><strong>val oldDb = SQLiteDatabase.create(null)<br>    FeedDatabase.create(oldDb, 1)<br>    FeedDatabase.upgrade(SynchronousExecutor(), oldDb, newDb, 1, 2)</strong><br><br>    <em>// First indication that our migration<br>    // was successful - comments table was dropped<br>    </em>assertFalse(oldDb.checkTableExists(Comment.TABLE_NAME))<br>    oldDb.close()<br><br>    <em>// Second indication that our migration<br>    // was successful - we have the data in the new database<br>    </em>newDb.apply {<br>        val comments = commentDao().testFetchAll()<br>        assertEquals(1, comments.size)<br>        assertEquals(100, comments.first().id)<br>        assertEquals(&quot;Foo&quot;, comments.first().user)<br>        assertEquals(&quot;Bar&quot;, comments.first().message)<br>    }<br>}</pre><ul><li>We first call SQLiteDatabase.create() static method which creates an in-memory database, just like Room has.</li><li>Once we create the in-memory database, we create the schema in version <em>1</em>. If you recall, we previously wrote a static create method on FeedDatabase that takes an optional version.</li><li>Next, we execute the migration itself and right after that we make our first check to see that the old database table was indeed deleted. This is our first indication that the migration was successful.</li><li>Finally, we query our new Room database to see that the data was copied successfully.</li></ul><h3>Refactoring the Codebase to use Room DAO</h3><p>Our last step, which is probably also the longest and hardest step (of course depending on how tightly coupled is your old DAO implementation in your codebase), is to refactor our codebase to use the new Room DAO, CommentDao in this case. There’s nothing special to say about this step. My only advice is that you test as much as possible.</p><p>That’s it! Once you’re done with this step, you can proceed with your app’s release. Repeat this flow until your old database is completely migrated to the new one. Remember that you will have to keep your old SQLiteOpenHelper implementation, FeedDatabase in this case, pretty much forever due to the migrations, but otherwise you should be able to delete any other classes from your old ORM implementation.</p><p>The code in this article is available on Github:</p><p><a href="https://github.com/Nimrodda/gradual-room-migration">Nimrodda/gradual-room-migration</a></p><p>If you liked this article please remember to clap and follow me for more articles in the future.</p><p><a href="https://twitter.com/nimroddayan">https://twitter.com/nimroddayan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=133520c7260" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/gradually-migrate-to-room-the-missing-guide-133520c7260">Gradually Migrate to Room — The Missing Guide</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Gradle Tasks with Kotlin]]></title>
            <link>https://medium.com/android-news/custom-gradle-tasks-with-kotlin-e0f8659628a6?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f8659628a6</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Wed, 15 Nov 2017 06:11:12 GMT</pubDate>
            <atom:updated>2020-08-31T12:13:37.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*UlNDLLEKHZVYu6XvjlNKFA.jpeg" /></figure><h3>Gradle Tasks with Kotlin</h3><p>Recently, I had the need to send a Slack message from our CI server during our Android app build. Since Android is built with Gradle and in my opinion Gradle is just pure awesomeness, I thought why not just have a task that does just that.</p><p>The first thing I did was to look for a pre-made solution in the form of a Gradle plugin. I found one, but it wasn’t flexible enough as I wanted it to be. So I decided to create my own custom task to do that and while I’m at it have it written in Kotlin (of course :P).</p><h3>Project structure</h3><p>Creating a custom Gradle task can be <a href="https://docs.gradle.org/current/userguide/custom_plugins.html#sec:packaging_a_plugin">done in different ways</a>. You can just write Groovy code in your build.gradle or make it a bit nicer and have it in a separate Gradle file, say slack.gradle, and apply it to your app’s build.gradle with apply from: &#39;slack.gradle&#39;. But that would be Groovy and not Kotlin. Although there’s a <a href="https://github.com/gradle/kotlin-dsl">Gradle Kotlin DSL</a> work-in-progress, but after checking out the examples, I decided not to try it since it looks like it adds more code to build.gradle than it reduces and overall the DSL doesn’t look as nice as it looks in Groovy (just my opinion). I’ll definitely have another look when the DSL matures.</p><p>Another option is to make a standalone Gradle plugin project. That might have been my first choice, but I planned on having only one class that defines the custom task and less code is always better.</p><p>The last option is to have a folder called buildSrc in your project’s root folder and put everything there. This option felt like the way to go in this case.</p><h3>Setting up Kotlin support</h3><p>Surprisingly, I couldn’t find anything about how to hook up Kotlin with Gradle in the buildSrc setup. Most of the tutorials I found were talking about creating a Gradle plugin project with Kotlin and then there was the Gradle Kotlin DSL project, etc. Hence I decided to write my own tutorial.</p><p>First, create a folder called buildSrc in your project’s root. This folder is automatically detected by Gradle so you don’t need to configure it anywhere. Now create a build.gradle file inside buildSrc. We will use it to set up the Gradle Kotlin plugin and library dependencies that our custom task will use. In this case, I’m going to depend on okHttp to do the networking.</p><pre>buildscript {<br>    ext.kotlin_version = &#39;1.1.51&#39;<br>    repositories {<br>        jcenter()<br>    }<br>    dependencies {<br>        classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot;<br>    }<br>}<br><br>apply plugin: &#39;kotlin&#39;<br><br>ext {<br>    okHttpVersion = &quot;3.8.1&quot;<br>}<br><br>repositories {<br>    jcenter()<br>}<br><br>dependencies {<br>    <strong>implementation gradleApi()</strong><br>    implementation &quot;com.squareup.okhttp3:logging-interceptor:$okHttpVersion&quot;<br>    implementation &quot;com.squareup.okhttp3:okhttp:$okHttpVersion&quot;<br>    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version&quot;<br>}<br><br>compileKotlin {<br>    kotlinOptions {<br>        jvmTarget = &quot;1.8&quot;<br>    }<br>}<br>compileTestKotlin {<br>    kotlinOptions {<br>        jvmTarget = &quot;1.8&quot;<br>    }<br>}</pre><ul><li>Note that we also have dependency on <strong>gradleApi() </strong>which is a built-in method in Gradle.</li></ul><p>One you’re done with build.gradle, create folders src/main/kotlin inside buildSrc. Sync your project with Gradle in Android Studio (the little green icon) and let’s continue to the custom task class creation. After the sync, Android Studio has identified src/main/kotlin as a source folder so you can now create packages there. Create your package however you want, mine is going to be org.codepond.gradle.slack.</p><h3>Writing the task class in Kotlin</h3><p>Inside this package you created, create Kotlin class SlackTask.kt with the following code:</p><pre>package<strong> </strong>org.codepond.gradle.slack<br><br>import<strong> </strong>okhttp3.MediaType<br>import<strong> </strong>okhttp3.OkHttpClient<br>import<strong> </strong>okhttp3.Request<br>import<strong> </strong>okhttp3.RequestBody<br>import<strong> </strong>okhttp3.logging.HttpLoggingInterceptor<br>import<strong> </strong>org.gradle.api.DefaultTask<br>import<strong> </strong>org.gradle.api.tasks.TaskAction<br><br><strong>open</strong> class<strong> </strong>SlackTask : <strong>DefaultTask()</strong> {<br>    <strong>lateinit</strong> var messageText: String<br>    <strong>lateinit</strong> var webhookUrl: String<br><br>    <strong>@TaskAction</strong><br>    fun sendMessage() {<br>        val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { m -&gt; logger.debug(m) })<br>        logger.level = HttpLoggingInterceptor.Level.BODY<br>        val okhttp = OkHttpClient.Builder().addInterceptor(logger).build()<br>        val body = RequestBody.create(MediaType.parse(&quot;application/json&quot;), &quot;{\&quot;text\&quot;:\&quot;${messageText.replace(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;)}\&quot;}&quot;)<br>        val request = Request.Builder()<br>                .url(https://medium.com/webhookUrl)<br>                .post(body)<br>                .build()<br>        okhttp.newCall(request).<strong>execute()</strong><br>    }<br>}</pre><p>A few important things to notice here (marked in bold):</p><ul><li>The class must be defined as open. Kotlin classes cannot be extended by default (similar to final class in Java) and if not set correctly, Gradle will try to proxy your class and fail the build.</li><li>We extend DefaultTask since well, it’s a Gradle task ;)</li><li>We annotate our entry method with @TaskAction so Gradle knows what to execute.</li><li>We declare the properties messageText and webhookUrl as lateinit var properties since these two properties are mandatory in the task spec and we don’t want any default values. Gradle will make sure that these properties are assigned when configuring the task. If we don’t set them, the build will fail saying that these properties were not set. If you want to have optional properties for your task, you can annotate them with @Optional annotation.</li><li>Now considering the code itself, we set up OkHttp with a logging interceptor that logs directly to Gradle debug level and then it’s just standard OkHttp POST request. You can use JSON marshalling library if you have a complex JSON, but for this example, it was easier to just write it by hand.</li><li>It’s important to notice that the request is executed synchronously with execute() instead of enqueue(). Otherwise if you do it async, the task will just complete with build successful without actually ever sending the request (or sending it, but not receiving the response since we’re not blocking the thread).</li></ul><h3>Using the custom task in build.gradle</h3><p>Now to the last part. We’ve got the custom task class in place, now we need to use it in our build.gradle. To do that you have to include an import statement at the beginning of the build.gradle file.</p><blockquote>This wasn’t so obvious since in the official Gradle docs, it says that all classes under buildSrc will be available directly in build.gradle, but at least according to my tests this was true only when the class was written in<strong> Groovy — </strong>and<strong> not in Kotlin</strong>.</blockquote><p>In your build.gradle (doesn’t matter if it’s the root or the app/module specific one — wherever you’d like to define this task) add the following:</p><pre><strong>import </strong>org.codepond.gradle.slack.SlackTask<br><br>task helloSlack(type: SlackTask) {<br><em>    </em>messageText = &quot;Hello there!&quot;<br><em>    </em>webhookUrl = &quot;your webhook URL here&quot;<br>}</pre><blockquote>More info on Slack Incoming Webhooks and how to generate them <a href="https://api.slack.com/incoming-webhooks">here</a>.</blockquote><p>And now to run this task from command line type: ./gradlew helloSlack.<br>If you’re experiencing issues making the request, remember we set up OkHttp logging interceptor output to Gradle debug level logger. To show the logs run the same command with -d e.g.: ./gradlew helloSlack -d.</p><p>There you have it, you’ve successfully written a custom Gradle task in Kotlin that doesn’t require you to have a separate Gradle plugin project setup. Everything in one project under Android Studio!</p><p>If you liked this article please like and follow me here and on twitter.</p><p><a href="https://twitter.com/nimroddayan">https://twitter.com/nimroddayan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f8659628a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/custom-gradle-tasks-with-kotlin-e0f8659628a6">Custom Gradle Tasks with Kotlin</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android and Dagger: AndroidInjection]]></title>
            <link>https://medium.com/android-news/android-and-dagger-2-10-androidinjector-5e9c523679a3?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e9c523679a3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Tue, 28 Mar 2017 21:21:46 GMT</pubDate>
            <atom:updated>2020-05-14T10:28:28.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dagger Android Migration Guide</h3><blockquote>This tutorial has been updated for Dagger 2.21</blockquote><p>Dagger 2.10 introduced <a href="https://google.github.io/dagger/android"><em>dagger-android</em></a>, a new module specifically for Android that comes in addition to the main dagger module and compiler. In this tutorial we will go through the steps needed to get started with the new module — assuming you’re already familiar with Dagger.</p><p>This tutorial is focused on Activity injection, but might as well serve as a reference for other Android components.</p><p><a href="https://github.com/Nimrodda/dagger-androidinjector">Nimrodda/dagger-androidinjector</a></p><h3>Common Dagger Setup</h3><p>A common Dagger setup on Android normally involves an Application Component and an Application Module where the former is used to inject Android components, such as Activity, Fragment, etc.</p><pre>@Component(modules = { AppModule.class })<br>interface AppComponent {<br>    @Component.Builder<br>    interface Builder {<br>        @BindsInstance Builder application(App application);<br>        AppComponent build();<br>    }    <br>    void inject(FeatureActivity featureActivity);<br>}</pre><pre>@Module<br>abstract class AppModule {<br>    @Provides <br>    static Context provideContext(App application) {<br>        return application.getApplicationContext();<br>    }</pre><pre>    @Singleton <br>    @Provides <br>    static SomeClientApi provideSomeClientApi() {<br>        return new SomeClientApiImpl();<br>    }<br>}</pre><pre>public class App extends Application {<br>    private AppComponent appComponent;</pre><pre>    @Override<br>    public void onCreate() {<br>        super.onCreate();<br>        appComponent = DaggerAppComponent<br>            .<em>builder</em>()<br>            .application(this)<br>            .build();<br>    }</pre><pre>    public AppComponent getAppComponent() {<br>        return appComponent;<br>    }<br>}</pre><p>Since the Android framework instantiates these components for us, we have to perform member injection, i.e. annotating package visible class fields with @Inject-annotation like so:</p><pre>public class FeatureActivity extends AppCompatActivity <strong>{</strong><br>  @Inject SomeClientApi mSomeClientApi; </pre><pre>  @Override<br>  public void onCreate<strong>(</strong>Bundle savedInstanceState<strong>)</strong> <strong>{</strong><br>    super<strong>.</strong>onCreate<strong>(</strong>savedInstanceState<strong>);</strong><br>    <strong>((</strong>App<strong>)</strong>getApplication<strong>())</strong><br>        <strong>.</strong>getAppComponent<strong>()</strong><br>        <strong>.</strong>inject<strong>(</strong>this<strong>);</strong><br>  <strong>}</strong><br><strong>}</strong></pre><p>This pattern however breaks a core principle of dependency injection: <strong>a class shouldn’t know anything about how it is injected</strong>. The newly introduced <em>dagger-android </em>module specifically comes to address this problem — decoupling the injected class from its injector.</p><h3>Using the new dagger-android module</h3><p>First thing, add the following Gradle dependencies to your build.gradle:</p><pre>// Dagger core dependencies<br>annotationProcessor &#39;com.google.dagger:dagger-compiler:2.21&#39;<br>implementation &#39;com.google.dagger:dagger:2.21&#39;</pre><pre>// Dagger Android dependencies<br>annotationProcessor &#39;com.google.dagger:dagger-android-processor:2.21&#39;<br>implementation &#39;com.google.dagger:dagger-android:2.21&#39;<br>implementation &#39;com.google.dagger:dagger-android-support:2.21&#39;</pre><p>The setup of the new module requires more than just one component and one module in our project. Each Activity will require its own sub-component which is then hooked up to the Application component. My recommendation is to have the following class structure:</p><pre>/<br>| App (extending Application)<br>| AppComponent<br>| AppModule<br>| <strong>ContributeAndroidInjectorsModule // 3</strong><br>+ feature/<br> | <strong>FeatureModule // 2</strong><br> | <strong>FeatureActivityModule // 1<br> </strong>| FeatureActivity</pre><p>As we can see we have 3 more classes (marked in bold) added on top of the typical setup discussed in the previous section. Each feature has its own sub component and module.</p><blockquote>I’m using the term “Feature” to describe one screen (or Activity) in the app.</blockquote><ol><li><strong>FeatureActivityModule</strong></li></ol><p>As mentioned earlier, each Activity now requires its own sub-component. Dagger includes a convenience annotation that will signal Dagger to generate the sub-component for us. This is done like so:</p><pre>@Module<br>public abstract class FeatureActivityModule {<br>    @ActivityScope<br>    @ContributesAndroidInjector(modules = { FeatureModule.class })<br>    abstract FeatureActivity contributeFeatureActivityInjector();<br>}</pre><p>2. <strong>FeatureModule</strong></p><p>In this module we set up all the bindings we need in the Activity itself. Unless this module is not used in other components, the bindings in this module will be valid only for this Activity and its sub-components. Assuming we’re implementing the MVP pattern, this is how you’d normally bind the View:</p><pre>@Module<br>abstract class FeatureModule {<br><br>    @ActivityScope<br>    @Binds<br>    abstract FeatureView provideFeatureView(FeatureActivity featureActivity);<br>}</pre><p>3. <strong>ContributeActivityModule</strong></p><p>So far we told Dagger to generate a sub-component for our Activity but we haven’t hooked it up to Application Component. To do that, we need another module that will just hold all the Activity modules. This module will then be included in the Application component.</p><pre>@Module(includes = {<br>        FeatureActivityModule.class<br>        // Other Activity modules will be added here<br>})<br>abstract class ContributeActivityModule {<br>}</pre><p>4. <strong>AppComponent</strong></p><p>The application component set up (in Kotlin):</p><blockquote>I prefer to write Dagger modules in Java due to Kotlin’s lack of static modifier and the use of companion object requires additional @Module annotation nested in the same class, which I’m not a big fan of.</blockquote><pre>@Singleton<br>@Component(modules = [<br>    <strong>AndroidInjectionModule::class</strong>, // 1<br>    <strong>ContributeActivityModule::class</strong>, // 2<br>    AppModule::class<br>])<br>interface AppComponent <strong>: AndroidInjector&lt;App&gt;</strong> { // 3<br>    @Component.Builder<br>    abstract class Builder <strong>: AndroidInjector.Builder&lt;App&gt;()</strong> // 4<br>}</pre><p>Notice that there are a few changes in the AppComponent:</p><ul><li>We have to include <strong>AndroidSupportInjectionModule </strong>in the modules of the component for Dagger Android to work.</li><li>We include <strong>ContributeActivityModule </strong>which will hook up our Activity sub-component to AppComponent</li><li>AppComponent must inherit from AndroidInjector and define the Application class.</li><li>The Builder of AppComponent can optionally extend <strong>AndroidInjector.Builder </strong>and provide the Application class. This will simply save us a few lines of code since this base class already implements the common component builder with a method to set Application instance and another to build the component.</li></ul><p>5. We then modify our App class it extends DaggerApplication and implements the base methods like so:</p><pre>class App : DaggerApplication() {<br>    private val appComponent: AndroidInjector&lt;App&gt; by <em>lazy </em>{<br>        DaggerAppComponent<br>                .builder()<br>                .create(this)<br>    }<br><br>    override fun applicationInjector(): AndroidInjector&lt;out DaggerApplication&gt; {<br>        return appComponent<br>    }<br>}</pre><p>6. And finally, in FeatureActivity, we remove the code we had there for injecting the activity and inherit from DaggerAppCompatActivity instead of AppCompatActivity.</p><pre>class FeatureActivity : DaggerAppCompatActivity(), FeatureView {<br>    @Inject<br>    internal lateinit var presenter: FeaturePresenter<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>feature_activity</em>)<br>    }<br>}</pre><h3>Injecting custom arguments to Activity’s own component</h3><p>In some cases you want to inject arguments that are provided by the activity itself. The common way this was done previously was to pass the arguments to the module’s constructor before calling inject() on the activity’s component. For example, if we follow the MVP design pattern as described <a href="https://medium.com/@cervonefrancesco/model-view-presenter-android-guidelines-94970b430ddf">here</a>, our Presenter would take the View as part of its constructor arguments. This means that we’d need to pass the activity as an argument to the module constructor. Prior to <em>dagger-android</em>, this was done like so:</p><pre>@Module<br>class FeatureModule {<br>    private FeatureView view;<br><br>    public FeatureModule(FeatureView view) {<br>        this.view = view;<br>    }<br><br>    @Provides FeatureView provideView() {<br>        return view;<br>    }<br>}</pre><p>And in the presenter we would use constructor injection:</p><pre>class FeaturePresenter {<br>    private final FeatureView view;<br>    <br>    @Inject<br>    Presenter(FeatureView view) {<br>        this.view = view;    <br>    }</pre><pre>    public void doSomething() {</pre><pre>    }<br>}</pre><p>And lastly, build the component, pass a new instance of the module and inject the activity:</p><pre>public class FeatureActivity extends AppCompatActivity implements FeatureView {<br>    @Inject FeaturePresenter presenter;<br><br>    @Override<br>    protected void onCreate(@Nullable Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_main</em>);<br>        <strong>DaggerFeatureComponent.builder()<br>                .featureModule(FeatureModule(this)).build()<br>                .inject(this)</strong><br>        <br>        // presenter ready to be used<br>        presenter.doNothing();<br>    }<br>}</pre><p>But how do we do it with the new <em>dagger-android</em> module? After all, we don’t need to manually inject the Activity anymore and therefore we don’t have access to the module creation as before.</p><p>The answer is, we don’t need to do that anymore. With <em>dagger-android</em> module, the activity is already part of the graph. So what does it actually mean? You may recall that we have FeatureModule with the following set up to bind FeatureActivity everywhere a FeatureView is asked:</p><pre>@Module<br>public abstract class FeatureModule {<br>    @Binds<br>    abstract FeatureView provideFeatureView(FeatureActivity featureActivity);<br>    }<br>}</pre><p>But what if we want to pass arguments that are received via an Intent to the Activity to the Presenter? Let’s say you have a unique ID that is passed to the activity via the activity’s Intent’s extras and the presenter needs it. For example, imagine that the presenter needs this ID to make an HTTP request. The way to do this is to use qualifiers with the @Named annotation. So our presenter would look like so:</p><pre>class FeaturePresenter {<br>    private FeatureView featureView;<br>    private String someId;<br><br>    @Inject<br>    public FeaturePresenter(FeatureView featureView, @Named(&quot;someId&quot;) String someId) {<br>        this.featureView = featureView;<br>        this.someId = someId;<br>    }<br><br>    public void foo() {<br>        featureView.showFoo();<br>    }<br>}</pre><p>The answer is simple, we add a Provides method to FeatureModule that will take a FeatureActivity instance in and get the value we need from the intent extras:</p><pre>@Module<br>abstract class FeatureModule {<br><br>    @ActivityScope<br>    @Binds<br>    abstract FeatureView provideFeatureView(FeatureActivity featureActivity);<br><br>    @ActivityScope<br>    @Provides<br>    @Named(&quot;someId&quot;)<br>    static String provideSomeId(FeatureActivity featureActivity) {<br>        return featureActivity.getIntent().getStringExtra(FeatureActivity.<em>EXTRA_SOME_ID</em>);<br>    }<br>}</pre><p>As mentioned before, this is possible since FeatureActivity is already in the graph.</p><h3>Injecting other than activity</h3><p>As mentioned in the beginning of this tutorial, Fragment injection as well as other Android components are out of the scope of this tutorial. The <a href="https://google.github.io/dagger/android">official documentation</a> covers fragments under <em>Injecting Fragment objects</em> and I highly encourage you to read it. There’s also more info on Services, Receivers and ContentProviders.</p><h3>Conclusion</h3><p>Dagger-android module is close as it gets to proper dependency injection on Android. If you’re starting a new project and are planning to use Dagger, you should definitely use Dagger-Android setup.</p><p>The official sample is a bit too simple to my taste so you’d probably want to check out <a href="https://github.com/Nimrodda/dagger-androidinjector">my own sample</a> instead.</p><p>If you liked this article please don’t forget to give some claps and follow me.</p><p><a href="https://twitter.com/nimroddayan"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e9c523679a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/android-and-dagger-2-10-androidinjector-5e9c523679a3">Android and Dagger: AndroidInjection</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Bound Services and MVP]]></title>
            <link>https://medium.com/android-news/android-bound-services-and-mvp-12ca9f70c7c7?source=rss-49d94df33780------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ca9f70c7c7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nimrod Dayan]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 14:03:18 GMT</pubDate>
            <atom:updated>2020-08-31T12:15:18.638Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently while working on a hobby project of mine, an XMPP chat client, I faced an issue fitting an <a href="https://developer.android.com/guide/components/bound-services.html">Android Bound Service</a> into MVP design pattern. The service took user input, processed it and finally passed the result to the Activity to be shown to the user. The project was implemented using MVP design pattern with Dagger2.</p><p>Due to the nature of Bound Services, being an Android component that is tightly coupled with the Activity, my main goal was to stick to MVP as much as possible and communicate with the service via the presenter. I couldn’t find any article that touched bound services in the context of MVP so I decided to share my own experience.</p><h3>More Lifecycle Callbacks</h3><p>Bound Services add extra lifecycle callbacks to the Activity via the <a href="https://developer.android.com/reference/android/content/ServiceConnection.html">ServiceConnection</a> interface that must be registered when binding the service to the Activity. This meant that I could only get the service instance when <a href="https://developer.android.com/reference/android/content/ServiceConnection.html#onServiceConnected(android.content.ComponentName,%20android.os.IBinder)">ServiceConnection#onServiceConnected</a>() was called. It became clear to me that Dagger isn’t going to fit here due to the presenter being injected with its dependencies when the Activity was created.</p><h3>Attach — Detach</h3><p>As Dagger was not an option, it meant I had to pass the service instance to the presenter whenever the service was connected. I already had <em>attach()</em> and <em>detach()</em> methods in place so I decided to pass the service instance with <em>attach()</em> when the service was connected and clear the reference in <em>detach()</em> when it was disconnected. Instead of calling <em>attach()</em>/<em>detach()</em> in <em>onStart()</em>/<em>onStop()</em> respectively, I simply moved the calls to <em>onServiceConnected()</em>/<em>onServiceDisconnected()</em> and replaced <em>attach()</em>/<em>detach()</em> calls with <em>bindService()</em>/<em>unbindService()</em>.</p><p>I wanted to maintain the presenter’s testability so that I could run the tests locally without Android framework dependency. Just like any other presenter dependency, the bound service was no different. I simply abstracted away the service implementation by creating a service interface and made the presenter work against that. This way, I could easily mock the service in the presenter’s unit tests.</p><p>This solution worked very nicely. The only downside which I found so far is the necessity to do null checks before every service call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ceb198e4b47ed08d887a29e92706b3/href">https://medium.com/media/91ceb198e4b47ed08d887a29e92706b3/href</a></iframe><p>In the code above, you can see that when <em>ChatService</em> is bound, it returns <em>LocalBinder</em> instance which has <em>getService()</em> method that returns the service interface. The actual service implementation is implemented in another class and is injected to <em>ChatService#onCreate()</em> using Dagger. This way, you can unit test the service implementation in isolation — independently from the <a href="https://developer.android.com/reference/android/app/Service.html">Service</a> lifecycle. <em>MessagingService</em> and <em>MainPresenter</em> implementations were left for brevity.</p><p>I’d be really interested to hear how others have handled Bound Services with MVP so please leave your feedback in the comments section below.</p><p><strong>Sample App</strong></p><p>Here’s a <a href="https://github.com/Nimrodda/MaNishMa">sample messaging app</a> that I made which utilizes this pattern.</p><p><strong><em>Further reading</em></strong><br>If you’re looking for more info about Android MVP, I highly recommend this <a href="https://medium.com/@cervonefrancesco/model-view-presenter-android-guidelines-94970b430ddf#.2f9vy8eab">comprehensive article</a> by <a href="https://medium.com/u/c5aad32f276f">Francesco Cervone</a>.</p><p><a href="https://twitter.com/nimroddayan">https://twitter.com/nimroddayan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ca9f70c7c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/android-bound-services-and-mvp-12ca9f70c7c7">Android Bound Services and MVP</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>