<?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 Mina Kamel on Medium]]></title>
        <description><![CDATA[Stories by Mina Kamel on Medium]]></description>
        <link>https://medium.com/@minakamel?source=rss-efe1b975e3ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aRyKCjAU-wZAMHeOa64Wug.jpeg</url>
            <title>Stories by Mina Kamel on Medium</title>
            <link>https://medium.com/@minakamel?source=rss-efe1b975e3ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 11:14:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@minakamel/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[Updating a LazyColumn from a Flow]]></title>
            <link>https://medium.com/@minakamel/updating-a-lazycolumn-from-a-flow-838fa0ce00dc?source=rss-efe1b975e3ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/838fa0ce00dc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[lazycolumn]]></category>
            <dc:creator><![CDATA[Mina Kamel]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 18:33:21 GMT</pubDate>
            <atom:updated>2025-02-04T18:38:42.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOwaBYZaQMlfRxsmrhHMow.jpeg" /></figure><p>In this article, I’ll explain how to update a <em>LazyColumn</em> with new items received from a flow. The flow here simulates an endpoint or a data source that emits one item at a time with some delay. With every emission, the <em>LazyColumn</em> will be updated.</p><h3>Behaviour</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQbkUIXyFIY8sR757Sqe2A.gif" /></figure><h3>Flow Mock</h3><p>The Source class has <em>MutableSharedFlow</em> of strings (names) which others can collect. Upon calling start it emits a name with a delay:</p><pre>class Source {<br>    val namesFlow: MutableSharedFlow&lt;String&gt; = MutableSharedFlow()<br><br>    suspend fun start() {<br>        delay(1000)<br>        namesFlow.emit(&quot;Michael&quot;)<br>        delay(1000)<br>        namesFlow.emit(&quot;Hassan&quot;)<br>        delay(1000)<br>        namesFlow.emit(&quot;Mark&quot;)<br>        delay(1000)<br>        namesFlow.emit(&quot;Ahmed&quot;)<br>        delay(1000)<br>    }<br>}</pre><h3>Starting the flow</h3><p>In the MainActivity, we’ll create an instance of <em>Source</em> and call start. Since <em>start() </em>is a suspend method as it emits a Flow, we have to wrap the call in <em>lifecycleScope.launch</em></p><pre>val source = Source()<br><br>lifecycleScope.launch {<br>    source.start()<br>}</pre><h3>Compose:</h3><p>In order to collect flows in compose, we need to wrap our collection in <em>LaunchedEffect(Unit). </em>This will make sure that the flow collection is tied to the life cycle of the composable:</p><pre> LaunchedEffect(Unit) {<br>    source.namesFlow.collect {<br>           // We can&#39;t just update the lazy column here, keep reading.<br>           // We&#39;ll get back to it.<br> }<br>}</pre><h3>The LazyColumn:</h3><p>Let’s create a <em>LazyColumn </em>that fills the screen with contents cenetred horizontally:</p><pre>LazyColumn(<br>    modifier = Modifier<br>        .fillMaxSize()<br>        .padding(top = 46.dp),<br>    horizontalAlignment = Alignment.CenterHorizontally <br>) { <br>   // We should loop on the names here and add a Text composable but how? <br>   // Where are these names?<br>}</pre><h3>‘remember’:</h3><p>In order to update the <em>LazyColumn</em> above with the names collected from the <em>namesFlow </em>in compose, we need to persist them when they are collected. This can be achived by using <em>remember</em></p><p>Let’s add namesList which is a <em>mutableStateListOf. </em>It’s mutable because it changes whenever a new item is collected. We will persist it using <em>remember</em>.</p><pre>val namesList =<br>    remember { mutableStateListOf&lt;String&gt;() }<br><br>LaunchedEffect(Unit) {<br>    source.namesFlow.collect { name -&gt;<br>            namesList.add(name)<br> }<br>}</pre><h3>Back to the LazyColumn:</h3><p>Since compose is a declarative UI framework, the <em>LazyColumn</em> will recompose if told that it has dependency on the <em>namesList. </em>Therefore, whenever a new item is added to the list, it’s added to <em>LazyColumn. </em>How?</p><p>Remember the comment that asked how can we loop on the names? We have the <em>namesList</em> now, so let’s do it.</p><p>Using <em>items, </em>we can pass our <em>namesList </em>and add a Text composable for each item.</p><pre>LazyColumn(<br>    modifier = Modifier<br>        .fillMaxSize()<br>        .padding(top = 46.dp),<br>    horizontalAlignment = Alignment.CenterHorizontally <br>) { <br>    items(namesList) { names -&gt;<br>             Text(modifier = Modifier.padding(32.dp),text = item, fontSize = 20.sp)         <br>   }<br>}</pre><p>Now whenever the <em>Flow</em> emits and the <em>namesList</em> is updated, the update will be reflected in the <em>LazyColumn.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838fa0ce00dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for neater Android development — Part 1]]></title>
            <link>https://proandroiddev.com/tips-for-neater-android-development-part-1-34d3250b7943?source=rss-efe1b975e3ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d3250b7943</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mina Kamel]]></dc:creator>
            <pubDate>Fri, 04 May 2018 16:26:18 GMT</pubDate>
            <atom:updated>2018-06-25T09:43:28.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tips for neater Android development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAf3oqAqUgZ-wgqG5DceeA.jpeg" /><figcaption>Capri — April 2018 ©</figcaption></figure><p>Hi, it’s 2018 and we, Android developers, have been through a lot for nearly 10 years. Here are some tips that could make an Android app development neater (and possibly less painful).</p><h3>1. Deprecate. No regrets.</h3><p>Chances are, you were following MVP or your own implementation of MVVM or another design pattern or architecture when Google dropped the <a href="https://developer.android.com/topic/libraries/architecture/">Architecture Components</a> bomb last summer. You’ve tried it out in some private projects but you haven’t in your day to day work because you’re worried about the impact on features being built currently. Well, it’s time to let go.</p><p><strong>Versioning</strong> is key<strong>. </strong>Think of your base/core classes as APIs that are consumed by all the features your work on. If you have a current set of { BaseActivity, BaseFragment, BasePresenter…etc} consider it as <strong>v1.</strong></p><ul><li>Add a new directory called <strong>v1 </strong>and<strong> </strong>move your old common/base classes to it. Add <strong>@deprecated </strong>annotation to all of them.</li><li>Add a new directory called <strong>v2</strong> and start adding a new set.</li><li>Start using <strong>v1 </strong>in new features and then refactor older ones when there’s time.</li><li>Do the same with <strong>v2</strong> and <strong>v3</strong> whenever you feel there’s a need for upgrading.</li></ul><p>Deprecation and versioning are common practices in software development. You’ll notice a lot of deprecated classes in the Android SDK. Also the <a href="https://developer.android.com/topic/libraries/support-library/packages">support library</a> has different versions with same but updated set of classes.</p><p><strong><em>Tip</em></strong><em>: </em>Even if some classes are not going to change from v1 to v2, it’s better to keep (copy) the whole stack of classes unless the class is to be removed entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*IghpweI3FZCzobtm1RQ08Q.png" /><figcaption>Deprecated v1 and new v2</figcaption></figure><h3>2. Keep view models thin</h3><p><strong>Problem</strong>: View models (or presenters) can grow incredibly large and the code becomes hard to maintain or update.</p><p><strong>Solution</strong>: Think how can you delegate to another class, if it makes sense. The thinner the classes the better for our own sanity.</p><ul><li>In your View Models, <em>delegate</em> functionalities to <a href="https://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/">interactors</a> or use cases. This can be a network call or a database query or an arithmetic or logical operation or any peice of business logic. This way, view models become smaller and hence more readable and testable.</li><li>The interactor will also be easy to understand and test as it has only a single responsibility.</li><li>If you’re converting an object to another, extract the conversion/mapping to a mapper class. Common cases for this when preparing a network call parameter or when mapping one object from a layer to another.</li></ul><p>Here we’re mapping Recipe and DetailsInfo objects to DetailsViewEntity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b324d219418a38a19e6c4c8a6040d7/href">https://medium.com/media/74b324d219418a38a19e6c4c8a6040d7/href</a></iframe><ul><li>The functionality of <em>DetailsViewEntityMapper</em> will be tested separately</li><li><em>DetailsViewModel </em>will just call its <em>toDetailsViewEntity</em> method instead of owning the mapping logic<em>.</em></li><li><em>DetailsViewModel </em>(or presenter) test just needs to verify that the mapper method has been code. It doesn’t care about the actual implementation.</li></ul><h3>3. Use feature flags</h3><p>…and merge everything to your main branch (let’s call it <strong>develop</strong>). Instead of using feature branches and branching from them, why not have a switch that turns on or off the whole feature in <strong>develop</strong>?</p><p>There are two problems with feature branches:</p><p>1- You have to update them constantly from <strong>develop.</strong></p><p>2- You won’t, because you’re too busy working on the branch that you branched from the feature branch and by the time you get back to it, synchronisation could be messy and costly.</p><p><strong>Solution 1: Manual config</strong></p><ul><li>Add the flag to a constant file. It’s value is <em>false </em>in <strong>develop </strong>so the feature is not bothering anyone else.</li><li>Change the flag to true in your branch and when you release to QA.</li><li>Remove the flag or set it to true when feature is completely developed.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fb1d7212d94551fdeec264a73706493/href">https://medium.com/media/0fb1d7212d94551fdeec264a73706493/href</a></iframe><p><strong>Solution 2: Gradle config</strong></p><p>A better approach is to use <strong>Gradle</strong> to determine which build/flavor should has the feature enabled.</p><ul><li>In your build.gradle file find <strong>buildTypes.</strong></li><li>Assuming you have multiple build types, you can add <strong>buildConfigField</strong> with different values that enable/disable this feature.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7ad343cfc563862f5d7a682506bf26b/href">https://medium.com/media/a7ad343cfc563862f5d7a682506bf26b/href</a></iframe><ul><li>Gradle will generate the new field IS_FEATURE_A_ENABLED and will add it to <strong>BuildConfig </strong>file.</li><li>You can then reference it this way:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cf20298389df0ad12cae0ee3e1fa500/href">https://medium.com/media/4cf20298389df0ad12cae0ee3e1fa500/href</a></iframe><ul><li>The same could be done for <strong>productFlavors</strong> instead of <strong>buildTypes.</strong></li></ul><p><em>Note: </em>This also works for refactoring old code. Keep the old code and let the flag decide which code should run, legacy or refactored. After refactoring, delete the flag and throw the legacy code in the bin.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7b4FwtEI6W9yg%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7b4FwtEI6W9yg%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7b4FwtEI6W9yg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="331" frameborder="0" scrolling="no"><a href="https://medium.com/media/39b2c429d8c25952451b342fdeea1f74/href">https://medium.com/media/39b2c429d8c25952451b342fdeea1f74/href</a></iframe><h3>4. Use ArrangeBuilder pattern for tests</h3><p>Instead of this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa13455e4991d90346a02c37836149b/href">https://medium.com/media/baa13455e4991d90346a02c37836149b/href</a></iframe><p>Use this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5630d0c3cce42c506e1399fc3ba47ad7/href">https://medium.com/media/5630d0c3cce42c506e1399fc3ba47ad7/href</a></iframe><ul><li>Add an inner ArrangeBuilder class to each test file and move each <em>whenever</em> statement to a separate method.</li><li>The class might seem to make your test class longer but it will shorten your tests themselves and make them more descriptive.</li><li>Your test will feels like reading an English sentence and not code anymore.</li><li>Each <em>whenever</em> statement will be reusable and therefore less duplication all over tests.</li></ul><h3>5. Consider a new line \n</h3><p>How agonising is this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0461dd41a3ca2addb20fdb26a86b4eb/href">https://medium.com/media/f0461dd41a3ca2addb20fdb26a86b4eb/href</a></iframe><p>Probably some developer, in good faith, added this constructor with just two parameters not realising that it could grow to become this mess.</p><p>How about now?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f659a43ee14bb5cc0340efb78b93d94/href">https://medium.com/media/3f659a43ee14bb5cc0340efb78b93d94/href</a></iframe><p>Way cleaner and readable, right?</p><p><strong>Rx chains:</strong></p><p>Nope:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ebdb63641ec43b4029f6b43e95e60a0/href">https://medium.com/media/7ebdb63641ec43b4029f6b43e95e60a0/href</a></iframe><p>Yep:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea5bb66124a43cc274d899f4782da235/href">https://medium.com/media/ea5bb66124a43cc274d899f4782da235/href</a></iframe><p>Same goes for method parameters and builder patterns. Always consider if a new line would make the code look better.</p><p><em>To be continued…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d3250b7943" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/tips-for-neater-android-development-part-1-34d3250b7943">Tips for neater Android development — 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[Organising Android resources with Gradle and Kotlin]]></title>
            <link>https://proandroiddev.com/organising-android-resources-with-gradle-and-kotlin-26df1413d7ff?source=rss-efe1b975e3ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/26df1413d7ff</guid>
            <category><![CDATA[android-project-structure]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Mina Kamel]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 10:29:26 GMT</pubDate>
            <atom:updated>2018-05-02T13:22:23.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yu6t2G9mzr1WO6WIn4swhQ.jpeg" /><figcaption>Bali — February 2018 ©</figcaption></figure><p>If you’ve been working on an app for 3 or 4 years, you probably notice how the resources folder become messy. And while most developers focus on organising their Java/Kotlin files (by features or screens), resources are often left unattended.</p><p>One of the attempts to reduce the mess is using naming conventions for files. For example, in the layout files some would use:</p><ul><li>activity_*.xml</li><li>fragment_*.xml</li><li>item_*.xml</li></ul><p>or:</p><ul><li>feature1_screen1_activity.xml</li><li>feature1_screen2_fragment.xml</li><li>feature2_activity.xml</li></ul><p>While this ensures the file listing in Android Studio is relevant, the problem still persists as the project grows: Huge amount of (somehow sorted) files.</p><h3>Directories</h3><p>A nice approach is to actually organise resources the same logical way the Java/Kotlin files are organised. If we have this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*ewhOFw6UCHk_nbUkxpF24w.png" /><figcaption>Kotlin files for a Benefits activity that hosts two fragments: List and Details</figcaption></figure><p>Correspondingly, the resources look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*jHsZI7xF0KDN8xlrGLZgjw.png" /><figcaption>Resources for Benefits activity and list and details fragments</figcaption></figure><p>To achieve this:</p><ul><li>Switch to Project view in AS</li><li>Right click on <strong>main</strong> folder and add a <strong>Directory</strong>. We will call it<strong> res-features</strong>.</li><li>Add another directory with the feature name <strong>metal</strong>.</li><li>Finally, add as many directories for each screen.</li></ul><p>Inside each screen directory, add the standard Android resources folders that used to be inside the original <strong>res</strong> folder like <strong>layout</strong>, <strong>drawable-xhdpi</strong>, <strong>values</strong>… whatever is needed for this screen.</p><p>If there are resources used by multiple screens, keep them in the parent directory. For example, the strings of the metal feature are grouped in one file and its content is used by all the metal screen, so we will put it in the parent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*KsiJLKjw83hF76I_6J_1sA.png" /><figcaption>metal_strings.xml has strings for metal benefits, claims, membership and upgrade screens, keep it outside but under “values”, one of the standard Android resources folders.</figcaption></figure><h3>Gradle setup</h3><p>We need to let Android studio that it should look into the new directories instead of the default “res” to find the resource files. To do so, go to the build.gradle file and locate <strong>sourceSet </strong>and<strong> </strong>the directories of each screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*VIF2h_gQLmkEbzXDpvqMog.png" /></figure><p>This could really grow huge and ugly though. Not could, it will.</p><h3>Extraction: Approach 1 (All Gradle)</h3><p>What if we extract these directories to another file? Gradle can help us make this look neater.</p><ul><li>Go to root directory of the module.</li><li>Add new directory, call it <strong>resourcessystem</strong></li><li>Add new new file, in this case, we’ll call it <strong>metalresources.gradle</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5db993dd908915f140d90fb5943a0cae/href">https://medium.com/media/5db993dd908915f140d90fb5943a0cae/href</a></iframe><ul><li>In the <strong>build.gradle </strong>file add:</li></ul><pre>apply from: &#39;resourcessystem/metalresources.gradle&#39;<br>def metalResources = rootProject.ext.metaldirs</pre><ul><li>Finally, in the <strong>sourceSets</strong>:</li></ul><pre>sourceSets {<br><br>    main {<br>        ....<br>        res.srcDirs = metalResources<br>    }<br>}</pre><h3>Extraction: Approach 2 (Gradle + Kotlin)</h3><p>A better way is to group these directories into separate Kotlin arrays of strings. Each array represents a feature.</p><ul><li>Add a <strong>buildSrc</strong> directory to the project’s root directory.</li><li>Inside <strong>buildSrc</strong> add a file called <strong>build.gradle.kts </strong>and enable the kotlin plugin inside it and sync:</li></ul><pre>import org.gradle.kotlin.dsl.<em>`kotlin-dsl`<br><br></em>plugins <strong>{<br>    </strong><em>`kotlin-dsl`<br></em><strong>}</strong></pre><ul><li>Add directories <strong>src</strong>&gt;<strong>main</strong>&gt; <strong>java&gt;resources</strong>.</li></ul><p>Inside resources add a new Kotlin Object file that has one array list of the feature’s resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8265c19edcbd7124c831c43ebb010fff/href">https://medium.com/media/8265c19edcbd7124c831c43ebb010fff/href</a></iframe><blockquote>Do the same for each feature to keep the files thin and relevant</blockquote><ul><li>In <strong>build.gradle</strong> replace the directories with reference to all <strong>dirs</strong> of each file</li></ul><pre>import resources.*</pre><pre>sourceSets { <br>         .....<br>        res.srcDirs = Metal.<em>dirs </em>+ Savings.dirs + Insurance.dirs<br>    }<br>}</pre><h3>Two final notes:</h3><ul><li>You can add a <strong>res-common</strong> folder for all the common layouts, drawables, values… etc. It goes at the same level with <strong>res-features</strong>.</li><li>If you’re planning to modularise your project by features, this approach is actually a good start. When you start modularising, all you need is to copy each feature folder into the module.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26df1413d7ff" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/organising-android-resources-with-gradle-and-kotlin-26df1413d7ff">Organising Android resources with Gradle and Kotlin</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[Reducing ViewModel provision boilerplate in Google’s GithubBrowserSample]]></title>
            <link>https://proandroiddev.com/reducing-viewmodel-provision-boilerplate-in-googles-githubbrowsersample-549818ee72f0?source=rss-efe1b975e3ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/549818ee72f0</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Mina Kamel]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 15:09:12 GMT</pubDate>
            <atom:updated>2018-05-11T08:14:06.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnRbP52SQRSxlgfZO-hDTw.png" /><figcaption>Berlin — January 2017 ©</figcaption></figure><p>In a <a href="https://medium.com/@minakamel/how-to-inject-bundle-arguments-to-viewmodel-607429829cf0">previous</a> post, I’ve discussed how to inject parameters to view model constructor using ViewModelProvider.Factory and dagger. But is there a better way to avoid having to write a custom implementation to ViewModelProvider.Factory for every view model?</p><h3>Yes, there is</h3><p>In the aforementioned <a href="https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/viewmodel/GithubViewModelFactory.java">Github Browser Sample</a>, you can find a generic implementation of ViewModelProvider.Factory that saves us implementing one with every view model.</p><p>The way it’s used afterwards in SearchFragment, RepoFragment and UserFragment looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b4e1db70249bfa2a0c0dba89a27520b/href">https://medium.com/media/3b4e1db70249bfa2a0c0dba89a27520b/href</a></iframe><p>In addition, we have to add a bind method for each view model we add to the app in the <a href="https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/di/ViewModelModule.java">ViewModelModule</a>.</p><h3>Good step, but is there more?</h3><p>Well, at this point. We would still need to write (No, don’t fool yourself: copy/paste) the factory injection and viewModel provision within each fragment/activity a long with adding a method in the ViewModelModule as mentioned.</p><p>With the sheer amount of these fragments and activities that our apps usually have, we might want to think of a smarter way of handling the view model. Here we go:</p><p>Let’s start by making Fragments (and Activities) a little bit generic by adding a BaseFragment class that takes <strong>&lt;T extends ViewModel&gt;</strong> as generic parameter. In addition, we’ll inject a generic viewModel to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b263529216c25ac321d96077c744d47d/href">https://medium.com/media/b263529216c25ac321d96077c744d47d/href</a></iframe><p>We should change SearchFragment, RepoFragment and UserFragment in the sample to extend from BaseFragment and remove the injected factory and view model provisioning from each.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34a0e9f592d84ed816eda004636b4ae4/href">https://medium.com/media/34a0e9f592d84ed816eda004636b4ae4/href</a></iframe><h3>ViewModelUtil?</h3><p>In the sample code, a <a href="https://github.com/googlesamples/android-architecture-components/blob/d7cd7a9414ef1eeba52a79ec76f6d9827cd50a36/GithubBrowserSample/app/src/androidTest/java/com/android/example/github/util/ViewModelUtil.kt">ViewModelUtil</a> class is used for creating view model factory for testing purposes. We’ll make use of it!</p><p>Let’s move it to production code (or make another copy of it). And then use it in our BaseFragment to create the factory. The BaseFragment should now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52725c060209244998bf8e684419e55c/href">https://medium.com/media/52725c060209244998bf8e684419e55c/href</a></iframe><p>You may have noticed that the view model is not set to the returned value of ViewModelProviders.of but that’s fine. After the viewModel is injected, calling <strong>of()</strong> will ensure the instance has been created.</p><p>Now in each child fragment, <strong>viewModel</strong> will be ready to be directly used without further coding.</p><p><em>Tip: Ideally, factory creation and view model provisioning should be done in fragment’s onViewCreated specially if the activity hosts multiple fragments.</em></p><h3>No need for GithubViewModelFactory or ViewModelModule!</h3><p>The ViewModelModule was used to provide a map of view models through dagger that is used by the GithubViewModelFactory. With this new setup, no need for either. All you need is to just use the viewModel instance directly in your fragment/activity!</p><h3>Fixing tests</h3><p>If you are like me, not a big fan of instrumentation tests and would rather focus on unit tests, you’re pretty much done here. If you’re not, you may want to continue reading.</p><p>The changes broke the SearchFragmentTest, RepoFragmentTest and UserFragmentTest for two reasons:</p><ol><li><strong>viewModelFactory</strong> is no longer a member of the child fragment but rather of the BaseFragment. To fix that, simply remove this line (we’ll find another way to bridge the view model):</li></ol><pre>searchFragment.viewModelFactory = ViewModelUtil.<em>createFor</em>(viewModel);</pre><p>2. The mocked view model in each test has nothing to do with the generic. view model we added to BaseFragment. Therefore we get this NPE when we run tests:</p><pre>java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.Class java.lang.Object.getClass()’ on a null object reference</pre><p>To fix we can add this method to the BaseFragment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71bdf5d4cd41486102e4f4f58ad2fd1a/href">https://medium.com/media/71bdf5d4cd41486102e4f4f58ad2fd1a/href</a></iframe><p>This allows us to hook the mocked view model to the fragment in the init method of the tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4764997c7596d8c761e4d5a9b446fcb7/href">https://medium.com/media/4764997c7596d8c761e4d5a9b446fcb7/href</a></iframe><p>That’s it, tests fixed!</p><h3>Bonus: Kotlinify!</h3><p>If you’re using Kotlin, the ViewModelUtil can be replaced by a nice extension method that looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fc527a1c3cd16ba3b7a376ea780bc9c/href">https://medium.com/media/1fc527a1c3cd16ba3b7a376ea780bc9c/href</a></iframe><p>And the <strong>onActivityCreated</strong> method would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e7a2970124d00e9e696de864400280b/href">https://medium.com/media/7e7a2970124d00e9e696de864400280b/href</a></iframe><p>With this structure developers can easily hop into working on the logic of their views and view models with almost zero boilerplate code to prepare for that. Time to <strong>just</strong> code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=549818ee72f0" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/reducing-viewmodel-provision-boilerplate-in-googles-githubbrowsersample-549818ee72f0">Reducing ViewModel provision boilerplate in Google’s GithubBrowserSample</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 inject bundle arguments to ViewModel]]></title>
            <link>https://medium.com/@minakamel/how-to-inject-bundle-arguments-to-viewmodel-607429829cf0?source=rss-efe1b975e3ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/607429829cf0</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Mina Kamel]]></dc:creator>
            <pubDate>Wed, 27 Dec 2017 22:08:30 GMT</pubDate>
            <atom:updated>2017-12-27T22:18:51.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2N3OOt4XpEM6z6vYboYqA.jpeg" /><figcaption>Croatia — July 2017 ©</figcaption></figure><p>If you need to inject arguments that have just been passed to the Activity/Fragment directly to the ViewModel you can use the help of dagger to achieve this.</p><p>Using <strong>@BindsInstance </strong>you can specify an abstract function in the component following the builder pattern, and then override <strong>seedInstance </strong>to build with the value:</p><pre>@Subcomponent.Builder<br>abstract class Builder: AndroidInjector.Builder&lt;RatesFragment&gt;() {<br><br>    abstract override fun build(): RatesComponent<br><br>    @BindsInstance<br>    abstract fun currency(currency: String): Builder<br><br>    override fun seedInstance(fragment: RatesFragment) {<br>       currency(fragment.getCurrencyFromBundle())<br>    }<br><br>}</pre><p><em>Note</em>: This is equivalent to passing the arguments through the module’s constructor and then providing it through <strong>@Provides</strong> annotation. This is more common when using dagger’s older versions but the builder approach is <a href="https://google.github.io/dagger/api/2.11/dagger/BindsInstance.html">more efficient and cleaner</a>.</p><h3>Dagger to ViewModel:</h3><p>We’ve successfully passed the <strong>currency </strong>argument from the fragment to dagger. Next step: inject to view model.</p><p>To have a ViewModel with custom constructor (where you would pass arguments or interactors or anything else), you need a view model factory. In this factory we basically take the injected objects from dagger and tell it, the factory, to create the view model with these objects instead of the default constructor-less ViewModel :</p><pre>public class RatesViewModelFactory implements ViewModelProvider.Factory {<br><br>    @NonNull<br>    private final GetRatesList getRatesList;<br><br>    @NonNull<br>    private final String currency;<br><br>    @Inject<br>    public RatesViewModelFactory(@NonNull final GetRatesList getRatesList, @NonNull final String currency) {<br>        this.getRatesList = getRatesList;<br>        this.currency = currency;<br>    }<br><br>    @NonNull<br>    @Override<br>    public RatesViewModel create(@NonNull final Class modelClass) {<br>        return new RatesViewModel(getRatesList, currency);<br>    }</pre><p>In the Activity/Fragment, you would inject the factory and initialise the view model like this:</p><pre>class RatesFragment: BaseFragment() {<br><br>@Inject lateinit var viewModelFactory: RatesViewModelFactory</pre><pre>override fun initializeViewModelAndObserve() {<br>    viewModel = ViewModelProviders.of(this, viewModelFactory).get(RatesViewModel::class.<em>java</em>)</pre><pre>}</pre><p>There you go. Your view model’s constructor may look like this now:</p><pre>class RatesViewModel constructor(getRatesList: GetRatesList,<br>currency: String): ViewModel() {...}</pre><p><em>Note</em>: You may think you can just provide the argument through the module directly instead of using seedInstance because dagger (2.11+) injects the Activity/Fragment to its <a href="https://medium.com/@iammert/new-android-injector-with-dagger-2-part-1-8baa60152abe">graph</a>. Like this:</p><pre>@Provides<br>String providesCurrency(RatesFragment fragment) {<br>    return fragment.getCurrencyFromBundle();<br>}</pre><p>Unfortunately that’s not going to work because it creates a circular dependency and leaves dagger boggled. Why? <strong>RatesFragment</strong> has the <strong>RatesViewModelFactory</strong> as a dependency inside it (because it needs to initialise the view model). But the <strong>RatesViewModelFactory </strong>has the <strong>currency</strong> injected inside it which comes from <strong>RatesFragment</strong>. Dagger literally lost it when I did so. Better not.</p><p>Of course you might say: hey, why not just pass the argument this way?:</p><pre>override fun onViewCreated(view: View?, savedInstanceState: Bundle?{<br>    super.onViewCreated(view, savedInstanceState)<br><br>    viewModel.hereIsYourArgument(getCurrencyFromBundle())<br>}</pre><p>Well of course this would do the job but it’s cleaner to inject rather than pass through an argument. With injection, we know that this currency is really a <strong>dependency</strong> to the view model. Meaning, the view model can’t start doing its job without it. Moreover, the UI has stepped further away from the business logic, which means we can easily test the ViewModel with the currency value mocked inside it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607429829cf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>