<?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 Hasina H. R. on Medium]]></title>
        <description><![CDATA[Stories by Hasina H. R. on Medium]]></description>
        <link>https://medium.com/@hasina.anddev?source=rss-e9849fec9809------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*17j2nIB5owcAlQV_-jbo1w.png</url>
            <title>Stories by Hasina H. R. on Medium</title>
            <link>https://medium.com/@hasina.anddev?source=rss-e9849fec9809------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:12:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasina.anddev/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[Android Adventure: Flow of Views to Composable Flow]]></title>
            <link>https://medium.com/@hasina.anddev/android-adventure-flow-of-views-to-composable-flow-3b77bf2545da?source=rss-e9849fec9809------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b77bf2545da</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose-ui]]></category>
            <dc:creator><![CDATA[Hasina H. R.]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 13:48:37 GMT</pubDate>
            <atom:updated>2024-07-01T13:48:37.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*gK_PbOJiXGhwt2pKakCogA.jpeg" /><figcaption>Image found on <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/#aa-flex-wrap">css-tricks</a></figcaption></figure><p>My previous post titled “<a href="https://medium.com/@hasina.anddev/android-adventure-constraint-views-with-flow-74b7d982e452">Constraint Views with Flow</a>” shows the usage of <a href="https://developer.android.com/reference/androidx/constraintlayout/helper/widget/Flow">Flow</a> as a helper widget for ConstraintLayout to layout flexible UI. It was useful for the implementation of a schedule board in our example use case. However, this View system requires the usage of RecyclerView, Adapter, xml layouts and some custom performance handling. This post will show you an enhanced implementation of the same schedule board using Jetpack Compose 🚀: a toolkit API developed by Google to build the UI of apps on Android with Kotlin functions annotated as Composable. If you are not yet familiar with it, t<a href="https://developer.android.com/develop/ui/compose">he official documentation</a> is the right place to get started.</p><p>As UI App Development toolkits go on the Android Platform, Jetpack Compose is now the best way to implement user interface for Android apps. One of the main advantages is the implementation of complex UI with less code, which makes it faster to implement and smaller to maintain over time! If we take the schedule board screen as our example: RecyclerView, RecyclerView’s Adapter and UI xml definition for each item of date/hours in the list are not required anymore.</p><p>With Compose, the schedule board item looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e7db452723bf9779572bbda4648f6d/href">https://medium.com/media/e7e7db452723bf9779572bbda4648f6d/href</a></iframe><p>With provided data, the above block of code renders like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*ExemQNGu3Kqp_QdRkf1q-g.png" /></figure><p>The same functionality of <strong>androidx.constraint.layout.helper.widget.Flow </strong>in<strong> </strong>the View system is done by the composable <a href="https://developer.android.com/develop/ui/compose/layouts/flow">FlowRow</a>. Between lines 11 and 22, a forEach displays the list of hours into composable Buttons. And when the container runs out of horizontal space, these hour items flow into the next line as seen in the previous screenshot.</p><blockquote><strong>Note:</strong> ConstraintLayout still exists in Jetpack Compose but it is no longer useful here.</blockquote><p>To use the composable ScheduleBoardItem, instead of RecyclerView and its adapter, the composable <a href="https://developer.android.com/develop/ui/compose/lists#lazy">LazyColumn</a> (between lines 5 and 17) displays each item vertically with better performance (only visible item will be composed and laid out):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0113e4c5519ef3d63d49ea67a8aa680b/href">https://medium.com/media/0113e4c5519ef3d63d49ea67a8aa680b/href</a></iframe><p>For the sake of brevity, the theme colors implementation is not in these snippets and data is dummy values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f47b790ff05cd5c4b983050dbb48aef4/href">https://medium.com/media/f47b790ff05cd5c4b983050dbb48aef4/href</a></iframe><p>In a production app, a ViewModel should be used to provide real data: when it changes, UI would update accordingly. This is known as <a href="https://developer.android.com/develop/ui/compose/state">State</a>.</p><p>The screenshot below showcases the main Composables that compose the ScheduleBoardScreen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*_Bk57TOgAZpFZ_jRR9_aIg.png" /><figcaption>ScheduleBoardScreen</figcaption></figure><p>It’s done ! As you noticed, using Jetpack Compose reduces the amount of code considerably, especially in cases of complex UI layout such as the one we used as an example. Nowadays famous apps in Play Store are continuously migrated to Jetpack Compose, a sufficient proof that it is stable and it has become the new golden standard of UI development on Android, pushing the verbose Android View system to retirement. At <a href="https://www.frog.co/">frog</a>, our Android app developers are now convinced of the benefit of migrating older apps to Jetpack Compose. Of course, new apps starting from scratch should also select it by default!</p><p>See you soon and happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b77bf2545da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Adventure: Constraint Views with Flow]]></title>
            <link>https://medium.com/@hasina.anddev/android-adventure-constraint-views-with-flow-74b7d982e452?source=rss-e9849fec9809------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b7d982e452</guid>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[constraintlayout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Hasina H. R.]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 14:34:35 GMT</pubDate>
            <atom:updated>2023-09-28T14:41:20.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*gK_PbOJiXGhwt2pKakCogA.jpeg" /><figcaption>Image found on <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/#aa-flex-wrap">css-tricks</a></figcaption></figure><p>Certainly all Android app developers have already used RelativeLayout, LinearLayout, FrameLayout and ConstraintLayout as a container layout when implementing an app’s UI with XML. These containers help a lot to arrange or to position properly how View elements can be shown to an app’s user. Specially the ConstraintLayout can constrain Views to have relation to each other in an optimal way, even if the view hierarchy is complex. Nested view groups are not necessary, so called Flat hierarchy. Thanks to Google Android developer for this handy tool!</p><p>So let focus on ConstraintLayout by implementing an appointment schedule board user interface like you see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*11etbvp2RIXJNZxMikBFGg.png" /><figcaption>Appointment schedule board user interface</figcaption></figure><p>By analyzing this mock-up, we have a list of dates and each date has a list of random available hours. It’s straightforward to guess that the parent View of the layout is a RecyclerView with LinearLayoutManager in vertical orientation. But what about the group/list of hours? You may think to use, as parent View:</p><ul><li>LinearLayout with horizontal orientation. However, when no more space is available, it is not responsive to put its View children on a new row.</li><li>RecyclerView with GridLayoutManager. But the latter needs the exact number of columns that cannot be static for our sample due to different device screen’s size and resolution. The number of columns becomes tricky to compute. It depends on the width of the device’s screen, the width of hour’s View, the horizontal margins,…</li></ul><p>Let see another way to resolve the problem.</p><p>Have you already heard about <a href="https://www.w3schools.com/css/css3_flexbox.asp">CSS Flexbox</a> used by front web developer ?(Don’t be troubled, we won’t use WebView or CSS as solution… 🤪). The w3schools says:</p><blockquote>makes it easier to design flexible responsive layout structure without using float or positioning.</blockquote><p>We need the same feature in the Android View system. Good news! A Google’s library <a href="https://github.com/google/flexbox-layout">FlexboxLayout</a> brings the similar capabilities. Even more, starting from the version 2.0 of ConstraintLayout’s package, <a href="https://developer.android.com/reference/androidx/constraintlayout/helper/widget/Flow">Flow VirtualLayout</a> was added as a widget helper to position referenced widgets similarly to a chain. Setting the “flow_wrapMode” to “aligned” value resolves the problem of showing dynamically the list of hours in the schedule board through rows and columns. So no need to import another library if ConstraintLayout’s package is already available in the project.</p><p>The item’s layout of the main RecyclerView looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/080208417644f7f0d95152bfc2bb89c8/href">https://medium.com/media/080208417644f7f0d95152bfc2bb89c8/href</a></iframe><p>As you see in the code above, the Flow element is declared inside the ConstraintLayout with some attributes “<strong>flow_xxx</strong>” (see <a href="https://developer.android.com/reference/androidx/constraintlayout/helper/widget/Flow">the official doc</a> for more details on these attributes) to chain rows and columns with gaps. The attribute “<strong>constraint_referenced_ids</strong>” is not used because each hour’s View will be added in the ConstraintLayout and will be referenced dynamically. And it is done inside the RecyclerView’s Adapter, precisely in the ViewHolder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdda9997fa4809a583c59f30effa6a32/href">https://medium.com/media/cdda9997fa4809a583c59f30effa6a32/href</a></iframe><p>The interesting part is the method calls <strong>at the line 41 and 42</strong> where all views of hour are removed and added when “<strong>ScheduleBoardAdapter.onBindViewHolder</strong>” is called:</p><ul><li>In “<strong>updateByRemovingHourViews</strong>” method, each hour’s View is firstly removed from the Flow then removed from the ConstraintLayout.</li><li>In “<strong>updateByAddingHourViews</strong>” method, each inflated hour’s View is firstly added to the ConstraintLayout then added to he Flow. Note that Flow requires View with a reference id. <strong>In the line 71</strong>, this id is generated.</li></ul><p>The data model is pretty simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82e34bffffaa150d3c1f967eb8e625f3/href">https://medium.com/media/82e34bffffaa150d3c1f967eb8e625f3/href</a></iframe><p>The hour’s View layout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23185043d1930709bf99dd7ee2605ac7/href">https://medium.com/media/23185043d1930709bf99dd7ee2605ac7/href</a></iframe><p>We can say that it is enough to show the schedule board, however removing/adding all Views of hour is not efficient each time the RecyclerView binds item. As RecyclerView recycles items when an user is scrolling, we will also recycle hour’s View and use a garbage collector. The Adapter implementation becomes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb70b2b462fd425f9a9415f00f43e0c3/href">https://medium.com/media/eb70b2b462fd425f9a9415f00f43e0c3/href</a></iframe><p>What’s changed:</p><ul><li>With the implementation <strong>from the line 45 to 108</strong>, the hour Views is now recycled. How ? <strong>From the line 45 to 50</strong>, the size difference between already inflated hour Views <strong>(A)</strong> and the hours to be shown <strong>(B)</strong> determines the recycling strategy. If the <strong>(A)</strong>’s size is the same as <strong>(B)</strong>’s size, no need to inflate or to remove an hour’s View; <strong>(A)</strong> is updated with <strong>(B)</strong> by “<strong>updateHourViews</strong>” method. In case <strong>(A)</strong>’s size is greater, the exceeding Views are removed and the remaining are updated with <strong>(B)</strong> by “<strong>updateByRemovingHourViews</strong>” method. Inversely, more Views are inflated and <strong>(A)</strong> is updated with <strong>(B)</strong> by “<strong>updateByAddingHourViews</strong>” method.</li><li><strong>At the line 17</strong>, the “<strong>hourViewGarbageCollector</strong>” garbage collector is declared as <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html">Deque</a>. Used as LIFO stacks, “<strong>updateByRemovingHourViews</strong>” method adds all removed hour Views in it (<strong>at the line 70</strong>) and “<strong>inflateHourView</strong>” method returns from it these collected View instances, when available (<strong>from the line 103 to 105</strong>). Like so it reduces hour’s View to be inflated when “<strong>updateByAddingHourViews</strong>” is called.</li></ul><p>It’s done! We have a working Adapter for the RecyclerView of the schedule board screen, I let you to implement the Activity or Fragment. A future post may talk about how to implement this schedule board screen with Jetpack Compose 🚀.</p><p>See you soon and happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b7d982e452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Adventure: Clean Arch with Dependency Injection in your Android App]]></title>
            <link>https://medium.com/@hasina.anddev/android-adventure-c30c19e6cc3a?source=rss-e9849fec9809------2</link>
            <guid isPermaLink="false">https://medium.com/p/c30c19e6cc3a</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Hasina H. R.]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 15:35:22 GMT</pubDate>
            <atom:updated>2023-09-21T15:47:11.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8cSGE5TbkwyWufn9pbMk7g.png" /><figcaption>Source kodeco.com</figcaption></figure><p>As a child, do you remember how many times your parents told you to clean your room? Many times I guess 😆.</p><p>For this time, I’ll do the same, but it will be about your Android project. So, in this post, I will show you how to have a clean, modularized Android app source code by combining the concept behind <strong>Clean Architecture</strong> and <strong>Dependency Injection</strong>. We will benefit from using <strong>Gradle </strong>as the build tool and <strong>Hilt </strong>as the dependency injection library.</p><p>For beginners or experts in Android application development, I would like to sum up what <strong>Clean Architecture</strong>, <strong>Dependency Injection</strong> and <strong>Hilt</strong> stand for. Also, I suggest you dig deeper into these topics by consulting other documentation for a better understanding.</p><blockquote><strong>Notice:</strong> Clean Architecture or Dependency Injection are not tied to the ecosystem of the Android platform for application development, but are related to software engineering.</blockquote><ul><li><strong>Clean Architecture:</strong> a fashion way to produce a clean, testable and shareable code (between projects or developers). It reduces the complexity of reading or understanding your source code project. It also avoids the use of one object instance only to fetch data, to show it in the UI, to save it, etc. But if you like your app’s architecture to be like a plate of “spaghetti”, no need to keep on reading this post 😂. So, the purpose is to separate each task per object instance in order to eventually, have a group of components that will fulfill a purpose when linked together. We call it: “ separation of concerns ”. For more details about Clean Architecture, read this <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Uncle Bob</a> blog.</li><li><strong>Dependency Injection:</strong> instead of creating an object instance to be used in a Class that you define by yourself, you get it by delegating the instantiation to another object (an injector) that can inject it for you. This technic decouples the dependency that you can have for one object to another with the usage of an interface. Consider this snippet as an illustration:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e3d93fc5c29a8f7c4cc54a35dc64fd6/href">https://medium.com/media/7e3d93fc5c29a8f7c4cc54a35dc64fd6/href</a></iframe><p>To instantiate <strong>CompanyUseCase</strong>, an instance of <strong>CompanyDataSource</strong> is needed and, for the latter, an instance of <strong>CompanyRemoteService </strong>is needed. We will see later how to inject these dependencies using <strong>Hilt </strong>as a library, in order to avoid boilerplate code writing and to have a common way to implement a dependency injection in an Android app.</p><ul><li><strong>Hilt: </strong>a<strong> </strong>library to implement dependency injection in your Android project’s code. It is announced by Google Android developer as the recommended way to do dependency injection in an Android app development. As build on top of <strong>Dagger,</strong> <strong>Hilt</strong> is like its spearhead and is officially part of the Jetpack libraries. Previous experience with Dagger is not required if you start with Hilt. Follow this Android’s <a href="https://developer.android.com/codelabs/android-hilt#0">codelab</a> to practice and to be familiar with the common keywords.</li></ul><p>Now, checkout this project <a href="https://github.com/herintsoa-razaf/hilt-application">repository</a> as a sample that you can build and run with Android Studio. In two parts, I will go through the implementation of this project to showcase how clean architecture can be implemented in an Android app. The unique feature in the app is a dummy feature that gets a company data from local or remote service and shows it with an Activity plus a ViewModel.</p><h4>Part 1: project structure with Gradle x Clean Architecture</h4><p>The sample has “<strong>app</strong>” as the android application module. We can stay with this module to implement a clean architecture, but we can easily break the concept because classes in a same module can import each other. An Activity class can directly import a DAO class to retrieve data. Of course, with Java, we may use the package protected access, but not with Kotlin (read this <a href="https://discuss.kotlinlang.org/t/kotlin-to-support-package-protected-visibility/1544">discussion</a>). So, another gradle modules exists for a specific purpose as described as follows:</p><ul><li><strong>domain: </strong>where we have the business classes named UseCase, Models/Entities, DataSource interfaces, Manager interfaces and other utility classes that are specific to the business logic. You may notice that, in this module, we must avoid, as much as possible, a dependency to a specific platform. Imagine that you can take this module as it is in an Android project and use it directly in a Web project without editing anything.</li><li><strong>local: </strong>represents the persistent local storage where we have data source implementation to retrieve data locally through local database, SharedPreferences, Files, etc without network communication. In this module, we have also the Models, Mappers to map local’s model to domain’s model (vice versa), other utility classes that are specific to this module and the DAOs (Data Access Object) which abstract the origin of retrieved local data.</li><li><strong>remote: </strong>represents every network communication layer to retrieve data from a server (through web services) or another APIs (using Bluetooth, NFC, etc). In this module, we have data source implementation, Models, Mappers to map remote’s model to domain’s model and vice versa, utility classes that are specific to this module and classes related to network calls.</li><li><strong>presenter: </strong>the gateway between the domain and UI module to present available data and where we have ViewModels, Models representing view’s data/state, Mappers to map domain’s model to UI’s model and vice versa and other utility classes specific to this module only.</li><li><strong>UI: </strong>where we have every Android Activities, Fragments, custom Views and other utility classes that are specific to this module class only to show the app content.</li></ul><p>One last module but not the least:</p><ul><li><strong>core: </strong>the base module of every previously mentioned module. Consider it as an aggregator of custom libraries for your app and that you can import into another Android project without modification. So it means that we should not find any implementation related to the business context of an application. In this module, we can have constant declarations, extension definitions, models and any kind of utility classes.</li></ul><p>The following picture describes the dependency between each module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*R-RI05wxCI4Z2tXRnTq7HA.png" /><figcaption>Modules relation © Hasina H. R.</figcaption></figure><p><strong>:app</strong> module has dependencies on core, UI, presenter, domain, remote, local.</p><p><strong>:ui </strong>module depends on core and presenter.</p><p><strong>:presenter</strong> module depends on domain and core.</p><p><strong>:remote</strong> module depends on domain and core.</p><p><strong>:local</strong> module depends on domain and core.</p><p><strong>:domain </strong>module<strong> </strong>depends on core.</p><p><strong>:core</strong> module is stand-alone.</p><p>To reflect this architecture, the dependency block of the gradle file for each module is shown by the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44e2e8b4fc32acca8ca46c0eccbee8d9/href">https://medium.com/media/44e2e8b4fc32acca8ca46c0eccbee8d9/href</a></iframe><h4>Part 2: Clean Architecture x Hilt</h4><p>With the configuration described before, the project modules would appear in Android Studio like this (where app module is the only one that is not an Android library):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*PAkaC0Eypjvrh6VMPU1Bvw.png" /><figcaption>Project modules © Hasina H. R.</figcaption></figure><p>Setting up Hilt:</p><ul><li>Dependencies are added to the project as described <a href="https://developer.android.com/training/dependency-injection/hilt-android#setup">here</a>. The same steps are applied for the modules other than the app module by editing each <strong>build.gradle</strong> file.</li><li>In the app module, the <strong><em>android.app.Application</em></strong> class is extended<em>,</em><strong><em> </em></strong>annotated with <strong>@HiltAndroidApp </strong>and declared in the Manifest file.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe3077cbe9d695095054408ef7e0482b/href">https://medium.com/media/fe3077cbe9d695095054408ef7e0482b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71835058df376aea38a3e9e498a69479/href">https://medium.com/media/71835058df376aea38a3e9e498a69479/href</a></iframe><p>In the UI module:</p><ul><li>there’s an Activity with Fragment attached to it. This Fragment is not mandatory. It shows a case of using Hilt with the Fragment component. The layout is simple:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*A2IHeU1URGCuoJvc-p-0dg.png" /><figcaption>User Interface © Hasina H. R.</figcaption></figure><p>With the company’s ID specified in the field, the OK button launches a company data fetching and the result is shown. All the process goes through the different modules mentioned previously. To allow Hilt to inject dependencies in the Activity and in the Fragment, <strong>@AndroidEntryPoint </strong>annotates each other respectively. Check the full implementation of these classes in the repository mentioned before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3595d9308c19f2d064d6650ba8ce370f/href">https://medium.com/media/3595d9308c19f2d064d6650ba8ce370f/href</a></iframe><p>In the presenter module:</p><ul><li>A ViewModel class named MainViewModel that extends <strong>androidx.lifecycle.AndroidViewModel </strong>and<strong> </strong>is annotated with <strong>@HiltViewModel </strong>and <strong>@Inject</strong> for its constructor to let Hilt inject an instance of it.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a3149db4d34e2d4a7f9cf85a2ff7486/href">https://medium.com/media/6a3149db4d34e2d4a7f9cf85a2ff7486/href</a></iframe><ul><li>In the MainFragment, the instance of this ViewModel is retrieved by using the Android Kotlin extension method <strong>Fragment.viewModels(). </strong>Underlying data can be then retrieved by the help of <strong>LiveData</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f403a38ce2ff24476643dce588cab176/href">https://medium.com/media/f403a38ce2ff24476643dce588cab176/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4724bc26d66682807712d73ceb89e78f/href">https://medium.com/media/4724bc26d66682807712d73ceb89e78f/href</a></iframe><ul><li>In the snippet above, the <strong>CompanyUseCase </strong>object<strong> </strong>from domain module and the <strong>Context </strong>object<strong> </strong>are injected by Hilt. To feed <strong>_company </strong>LiveData value, <strong>CompanyUseCase.getCompanyInfo() </strong>is called to return an object of a <strong>CompanyModel </strong>class from domain module. Then this model is mapped to <strong>Company</strong> object owned by the presenter module. The latter is the model used by the UI module to show a company’s data. The extension method <strong>mapToPresenter </strong>maps the variable members from <strong>CompanyModel</strong> to <strong>Company </strong>class with a computation logic or not:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/701e8188ee81cdab8b5c002ec8333145/href">https://medium.com/media/701e8188ee81cdab8b5c002ec8333145/href</a></iframe><ul><li>The file project structure in the presenter module should look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*5JLyzbyIur7dLh10UfM6uA.png" /></figure><p>In the domain module, packages, classes and interfaces are described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*eqwlH0yvp4CoyXc3HuNRHQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fbc8a1418bf1cc6d7ce448ab7d71eea/href">https://medium.com/media/4fbc8a1418bf1cc6d7ce448ab7d71eea/href</a></iframe><ul><li>To let Hilt inject an instance of <strong>CompanyUseCase</strong> when needed, its constructor is annotated with @<strong>Inject</strong>.</li><li>The <strong>CompanyModel </strong>class’s definition is as same as <strong>Company </strong>class for simplicity. If it was different, the mapper would compute the value of the model object member to instantiate the appropriate value of the object member target.</li><li><strong>CompanyLocalSource</strong> and <strong>CompanyRemoteSource </strong>are two interfaces that will be instantiated by Hilt after <strong>CompanyUseCase </strong>is instantiated and injected into the MainViewModel. The snippet below shows the <strong>DomainModule </strong>class (located in the <strong>di.modules </strong>package of<strong> </strong>the<strong> </strong>app module) that configures Hilt on how to instantiate an object implementing these interfaces:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5139f87af7c00a679b7a55485d6ea7ae/href">https://medium.com/media/5139f87af7c00a679b7a55485d6ea7ae/href</a></iframe><p>In the remote module, packages, classes and interfaces are described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*dQv7LP3sFv7sIYYRwtViEQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c6e5ec6e03f4d9676a3fca299e21b64/href">https://medium.com/media/6c6e5ec6e03f4d9676a3fca299e21b64/href</a></iframe><ul><li><strong>CompanyRemoteSourceImp</strong> is an implementation of <strong>CompanyRemoteSource</strong> interface and injected by Hilt during the <strong>CompanyUseCase</strong> instantiation (decoupled with the real implementation behind <strong>CompanyRemoteSource</strong>). Third-party library like Retrofit or Apollo can be used to call web services in a real implementation of the <strong>CompanyRemoteSource</strong>. To be brief, a dummy service <strong>CompanyDummyService</strong> is implemented and injected by Hilt during <strong>CompanyRemoteSourceImp</strong> instantiation. The <strong>RemoteModule</strong> class defined in <strong>di.modules</strong> package of the app module declares how Hilt can provide an instance of the service:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c534100bd81c04190fc2ab5ff59c61/href">https://medium.com/media/44c534100bd81c04190fc2ab5ff59c61/href</a></iframe><ul><li>You may notice that <strong>Company </strong>model class is the return type of the <strong>CompanyService#getCompanyDetails() </strong>method. Owned by the remote module, this model represents the fetched remote data and can not clash with the same model located in presenter module. Indeed, presenter and remote modules have no link to each other. However, every model from remote module needs to be mapped to a model owned by domain module. See the <strong>CompanyRemoteSourceImp#getCompany() </strong>implementation, the extension method <strong>Company#mapToDomain() </strong>is called to dispose the result as a <strong>CompanyModel</strong>.</li></ul><p>Last but not least, in the local module, packages, classes and interfaces are described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*n5AcD9ue-79bRyChxVIeTA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c95a85f8df14b7d3a27bbd2ad6e272d/href">https://medium.com/media/9c95a85f8df14b7d3a27bbd2ad6e272d/href</a></iframe><ul><li><strong>CompanyLocalSourceImp </strong>is an implementation of the interface <strong>CompanyLocalSource </strong>to persist the fetched data locally into a database or a File, etc. It is instantiated by Hilt and injected in <strong>CompanyUseCase</strong>. So, the latter is also<strong> </strong>decoupled with the real implementation of storing data. An implementation of the <strong>CompanyDao </strong>interface is also injected by Hilt to abstract the real API to persist data locally. If <strong>Room</strong> ORM is used, DAO class implementations will be generated automatically. But with <strong>Realm</strong>,<strong> </strong>for example, the DAO class must be written. For simplicity, a dummy DAO is implemented. <strong>LocalModule</strong> class defined in <strong>di.modules</strong> package of the app module declares how Hilt can provide an instance of the DAO:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e43e8d59ab0e6764a25dacd8975ceea5/href">https://medium.com/media/e43e8d59ab0e6764a25dacd8975ceea5/href</a></iframe><ul><li><strong>CompanyEntity </strong>is the model used to persist data and needs to be mapped to <strong>CompanyModel </strong>when getting it (see the method <strong>CompanyLocalSourceImp#getCompany()</strong>) and the latter to <strong>CompanyEntity</strong> when persisting it (see the method <strong>CompanyLocalSourceImp#save()</strong>). The mapping process is respectively done through extension methods <strong>CompanyEntity#mapToDomain()</strong> and <strong>CompanyModel#mapToLocal() </strong>defined in the <strong>CompanyMapper</strong> file located in the local module.</li></ul><p><strong>TL;DR </strong>If you haven’t done it yet, checkout the <a href="https://github.com/herintsoa-razaf/hilt-application">repo</a> for a full working project that also uses <strong>Kotlin Coroutines</strong> to handle background thread. It mixes Clean Architecture, Hilt and Kotlin Coroutines together.</p><p>The choice of a good architecture is recommended and better on a considerable project. Even at the beginning of the development process or during maintenance, a project with a structured source code is always pleasant and motivating. So stay “Clean“ as much as possible ! 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c30c19e6cc3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Adventure]]></title>
            <link>https://medium.com/ideas-by-idean/android-adventure-512bbd78b05f?source=rss-e9849fec9809------2</link>
            <guid isPermaLink="false">https://medium.com/p/512bbd78b05f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[architecture-components]]></category>
            <dc:creator><![CDATA[Hasina H. R.]]></dc:creator>
            <pubDate>Fri, 17 May 2019 20:58:21 GMT</pubDate>
            <atom:updated>2023-09-21T15:49:44.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Architecture Components : Kotlin Coroutines inside NetworkBoundResource</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trV4ki6ij0EZhga9X6mHiA.png" /><figcaption><a href="https://developer.android.com/jetpack/arch/">architecture components</a></figcaption></figure><p><strong><em>Prerequisites</em></strong> : Before reading this post, I suggest you to catch up with these fundamentals topics :</p><ul><li><a href="https://developer.android.com/topic/libraries/architecture">Android Architecture Components</a> : as Lifecycle-aware components, LiveData, ViewModel</li><li><a href="https://kotlinlang.org/docs/reference/coroutines-overview.html">Kotlin Coroutines</a> : Google shared a nice <a href="https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#0">codelabs</a> on how to implement it in an Android app</li><li>And <a href="https://developer.android.com/jetpack/docs/guide">this developer guide</a> talking about app architecture.</li></ul><p>… and, if you like, have some practice 😉</p><p>After I read the <a href="https://developer.android.com/jetpack/docs/guide">guide</a> talking about app architecture combined with Android Architecture Components, I started to adopt the same principle in some projects and I decided to throw away my old fashioned habit of putting too many code into my Activity class (yes shame on me 😅) in the app. The guide explains very well how we must implement our app into different components to respect separation of concerns and the single source of truth concept, even if the app has his data from the Network and/or from local database.</p><p>One of these components that I liked is the abstract class <a href="https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/repository/NetworkBoundResource.kt">NetworkBoundResource</a>. You will find an explanation of its utility in the <a href="https://developer.android.com/jetpack/docs/guide#addendum">guide’s last section</a>. Generally, the purpose is to have a process flow on when app should fetch fresh data from Network or local data is sufficient to show on the UI.</p><p>After understanding how Google’s developers implemented it, I decided to :</p><ul><li>migrate the background task’s implementation from Java’s executor util to amazing Kotlin coroutines</li><li>change the way of exposing data and its related loading/error status</li></ul><p>Two useful classes are used in the Google’s developer implementation :</p><ul><li><a href="https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/vo/Resource.kt">Resource</a> : for exposing data with status like success, loading and error</li><li><a href="https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/AppExecutors.kt">AppExecutors</a> : backed by Java’s Executor java.util.concurrent.Executor for making background task outside of the UI context.</li></ul><p>The problem I found with the Resource class implementation is that I can not emit the loading status without setting the data. Or by emitting the same data with a different loading status, the UI context risks to repeat the same process of showing data even if no changes occurred. I don’t like that. As a workaround, I created a new class named LiveResource :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/196d65b516f764a684b3d135fa61852d/href">https://medium.com/media/196d65b516f764a684b3d135fa61852d/href</a></iframe><p>With this class and the Kotlin Coroutines feature, the new NetworkBoundResource looks as the following snippet :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d5d1042bc6899cbae7e10330a937de2/href">https://medium.com/media/2d5d1042bc6899cbae7e10330a937de2/href</a></iframe><p>What did I change here ?</p><ul><li>the result member is not a MediatorLiveData&lt;Resource&lt;ResultType&gt;&gt; anymore but becomes a MutableLiveData. There are also LiveData for the loading state and the error which can occurred. And a coroutine Job member is added instead of the AppExecutor passed to the NetworkBoundResource constructor :</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31eff0b7d240f06cbe07bc88cfd32b97/href">https://medium.com/media/31eff0b7d240f06cbe07bc88cfd32b97/href</a></iframe><ul><li>In the init block, an instance of CoroutineScope is created and launched in the IO context as background task to get the data from Network and/or local database.</li><li>Some functions like fetchFromNetwork loadFromDb, etc became a suspend functions to support Coroutines non-blocking operations and the result type is not LiveData anymore.</li></ul><p>You can notice with this new implementation that it can now emit different status of the data loading process without the concerned data necessarily.</p><p>Before :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fac64f4b9c62b6389f10df976985e3f8/href">https://medium.com/media/fac64f4b9c62b6389f10df976985e3f8/href</a></iframe><p>After :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/765df6e4258b91e797aa1e79097825ea/href">https://medium.com/media/765df6e4258b91e797aa1e79097825ea/href</a></iframe><p>How to use it in a UserRepository ?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9edfc1a9d4a58b558022ee9d647febed/href">https://medium.com/media/9edfc1a9d4a58b558022ee9d647febed/href</a></iframe><p><strong>Notes : </strong>If you don’t want to expose UserEntity to the UI, you can map it to another object like UserUIModel :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a219a476c20d35c75d1d6f82b9678dd9/href">https://medium.com/media/a219a476c20d35c75d1d6f82b9678dd9/href</a></iframe><p>The ViewModel that uses this repository can have the following implementation :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deaa140ad0c0edc0e28972b7c05bdc19/href">https://medium.com/media/deaa140ad0c0edc0e28972b7c05bdc19/href</a></iframe><p>And finally, LiveData’s Observers are attached in the fragment onActivityCreated (or in the activity onCreate) to display to the user :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc221efaea8f05b2a37fac52d31dead7/href">https://medium.com/media/fc221efaea8f05b2a37fac52d31dead7/href</a></iframe><p>By separating the data result, the loading status and the error in different LiveData, you now have the opportunity to ignore easily one of them. For example, only data result is important so no need to observe loading status and error.</p><p><strong>Notes : </strong>In the snippets above, the service which executes web api call and the DAO for local data access are not detailed here. However, I will use Retrofit (with coroutines support plugin) and Room, respectively, to fulfill these functionalities.</p><p>That’s all ! Feel free to share and comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512bbd78b05f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ideas-by-idean/android-adventure-512bbd78b05f">Android Adventure</a> was originally published in <a href="https://medium.com/ideas-by-idean">Ideas by Idean</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>