<?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 Malik Motani on Medium]]></title>
        <description><![CDATA[Stories by Malik Motani on Medium]]></description>
        <link>https://medium.com/@malikmotani?source=rss-6d8dc69c056c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pdxWwONdd0nqIUUhGJyRZg.jpeg</url>
            <title>Stories by Malik Motani on Medium</title>
            <link>https://medium.com/@malikmotani?source=rss-6d8dc69c056c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:08:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@malikmotani/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[Coroutines Flow Cookbook Part 1: Introduction]]></title>
            <link>https://medium.com/@malikmotani/coroutines-flow-cookbook-part-1-introduction-f52db01b53d5?source=rss-6d8dc69c056c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52db01b53d5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <dc:creator><![CDATA[Malik Motani]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 08:19:02 GMT</pubDate>
            <atom:updated>2024-10-13T06:22:08.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnrZmND5F-UKPIS1yoprYQ.jpeg" /><figcaption>Unsplash: <a href="https://unsplash.com/@kazuend">kazuend</a></figcaption></figure><p>It’s been a while since the stable release of Coroutines in Android was available. Flow is also part of the latest Coroutines library. Basic knowledge of Coroutines is the prerequisite for Flow.</p><h3>What is Flow?</h3><p>Flow is an asynchronous stream of data that emits values to the consumer (collector) and gets completed with or without an exception.</p><p>For example, we have a feature in the app to download a file, and we are supposed to show progress in UI. The file download task will emit the progress of the file downloaded in percentages like 10%, 20%, etc. If the download task executes successfully, the file gets downloaded without expectation. In case of any error, our task will return an exception. Download Task will emit the progress and UI will be our consumer/collector to show progress.</p><pre>val downloadFileflow = flow {<br>        // start downloading<br>        // emit progress<br>        emit(25)<br>        // downloading...<br>        // ..............<br>        // emit progress<br>        emit(50)<br>        // downloading...<br>        // ..............<br>        // emit progress<br>        emit(100)<br>}</pre><h3>Basic Components of Flow</h3><ol><li>FlowBuilder</li><li>Operator</li><li>Collector</li></ol><p>Let&#39;s try to explore these components.</p><h4>FlowBuilder</h4><p>In the file-downloading example, the task created to download the file will emit the progress. In this scenario, Flow should be created at the Download task level, which in Android terminology would be in the data layer.</p><h4>Operator</h4><p>An operator will transform data from one format to another. In the context of downloading we will receive the stream of data from the Download Task which is supposed to be stored as a file in the Android file system. So here we will transform the stream to a file.</p><h4>Collector</h4><p>The Collector is the consumer or listener of the data emitted by FlowBuilder (which is transformed by the Operators). The collector also comes under the operator, which is known as the <strong>Terminal Operator</strong>.</p><p>Flow API source for the collector:</p><pre>public fun interface FlowCollector&lt;in T&gt; {<br>    public suspend fun emit(value: T)<br>}</pre><pre>public interface Flow&lt;out T&gt; {<br>    public suspend fun collect(collector: FlowCollector&lt;T&gt;)<br>}</pre><p>Let&#39;s take a small example,</p><pre>flow {<br>    (1..5).forEach {<br>        emit(it)<br>    }<br>}.map {<br>    it * it<br>}.collect {<br>    println(it.toString())<br>}</pre><p>The output of the above code will be as follows:</p><pre>1<br>4<br>9<br>16<br>25</pre><p>In the next installment of this series, we will look into more details of <strong>FlowBuilder. </strong>By the time keep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52db01b53d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast Lane to Dagger2 Part — 1 : Introduction]]></title>
            <link>https://medium.com/mindful-engineering/fastlane-to-dagger2-part-1-introduction-43be20c605b9?source=rss-6d8dc69c056c------2</link>
            <guid isPermaLink="false">https://medium.com/p/43be20c605b9</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Malik Motani]]></dc:creator>
            <pubDate>Sat, 23 May 2020 11:19:39 GMT</pubDate>
            <atom:updated>2020-06-25T09:04:44.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fast Lane to Dagger2 Part — 1 : Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*Z5KpAQRIedjcd_yT5EQotw.gif" /><figcaption>Steam: <a href="https://steamcommunity.com/sharedfiles/filedetails/?id=1474824793">The Fastest Man Alive</a></figcaption></figure><p>Dagger is a dependency injection framework developed by Square and later forked by Google and called it Dagger2. You might be knowing about dependency injection(DI) and might have used Butterknife for view injections but this one, It is for dependencies.<br>If you haven’t heard of DI yet, please don’t react this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*SVSZCTVx8oibbBwjhW0uOA.gif" /><figcaption>Giphy: <a href="https://giphy.com/gifs/reaction-what-despicable-me-SqmkZ5IdwzTP2">Despicable Me What GIF</a></figcaption></figure><p>We will get you informed about it, Let’s look at what it can help you with:</p><h4>Benefits of Dagger</h4><ul><li>Write testable code</li><li>Decouple class and its dependency</li><li>Design maintainable and reusable structure and that’s not it, there are so many advantages of Dagger.</li></ul><p>Here I’m going to explain a few basic things about DI</p><h4>What is a dependency?</h4><p>While developing real-time Apps, it may happen sometimes that our class may require an object of another class. Let’s understand this via an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*ybhAHba7ZsG-NYEP" /></figure><p>Here Class <strong>Black</strong> needs an object from class <strong>Red</strong>, <strong>Green,</strong> and <strong>Blue</strong>, to fulfill its purpose. It implies that class <strong>Black</strong> is dependent on <strong>Red</strong>, <strong>Green,</strong> and <strong>Blue</strong>. So, Dependency is an object that can be used.</p><h4>What is Dependency Injection?</h4><p>An injection is a mechanism to provide the object to the depending class.</p><p>A form of Inversion of Control, a design principle, which says that any class should be getting its dependencies from outside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*QYMR_4O-7Ee1aAZv" /></figure><p><strong>In other words, </strong>a class should not be instantiating another class within it, but rather there should be another configuration class that can provide with those instances.</p><p>So, in DI we will be writing a configuration that will instantiate our class on behalf of us.</p><h4>Modes of Dependency injection</h4><ul><li>Constructor injection: Injecting the constructor parameters</li><li>Field injection: Injecting the member variable (Required that it must not be private)</li><li>Method injection: Injecting the method parameter</li></ul><h4>Annotation</h4><ul><li>A <strong>class of metadata</strong>, introduced in Java 1.5, that can be associated with class, methods, fields, and even other annotations.</li><li>Those metadata can be accessed at <strong>runtime</strong> via <strong>Reflection</strong>.</li><li>But we were not known to the same capability of reading metadata at <strong>compile time</strong> via <strong>Annotation processors</strong>.</li></ul><h4>What do Annotation processors do?</h4><ul><li>Annotation Processors are code generators that eliminate boilerplate code by generating code for you at Compile Time. Really..!!</li><li>No performance Overheads at all (Compile Time nature).</li></ul><p>Even you can create your own Annotations and a Processor for it using this tutorial: <a href="https://stablekernel.com/the-10-step-guide-to-annotation-processing-in-android-studio/">The 10 step guide to annotation processing in android studio</a></p><p>Example</p><ol><li>Jake Wharton’s ButterKnife is an Annotation processor (@Bind(R.id.textView) TextView textView )</li><li>Android Architecture Component’s Room Persistence Library is an Annotation Processor (@Entity, @Dao)</li></ol><h4>Annotations with Dagger2</h4><ul><li><strong>@Module and @Provides:</strong> define classes and methods which provide dependencies</li><li><strong>@Inject:</strong> request dependencies. Can be used on a constructor, a field, or a method</li><li><strong>@Component:</strong> enable selected modules and used for performing dependency injection</li></ul><h3>What is a Component?</h3><ul><li>A public interface to your dependency graph</li><li>Best Practise: Exposes only your top-level dependency. Internal dependencies should remain under the hood.</li><li>In the example, we will create an <strong>AppComponent</strong></li><li>@Component: Tells Dagger that this interface is a Dagger Component and not an ordinary interface. Dagger will generate a subclass of this component with the implementation of Modules</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6375a94d9561f867f7e5ea72f6938480/href">https://medium.com/media/6375a94d9561f867f7e5ea72f6938480/href</a></iframe><p>But how will Component know from where to get the dependency of UserRepository? Answer is <strong>Module</strong></p><h3>Modules for dependencies</h3><ul><li>Provide those under the hood dependencies to the outermost dependency, like <strong>UserRepository</strong>.</li><li>In the example, we will have <strong>AppComponent</strong> to these modules as <strong>UserModule</strong>, <strong>NetworkModule,</strong> etc.</li><li><strong>@Provides</strong>: If any method in the module provides dependency, it should be annotated with @Provides</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb8b9f355d66fe4f511c9661a086fc1/href">https://medium.com/media/fcb8b9f355d66fe4f511c9661a086fc1/href</a></iframe><p>Manage External Dependencies</p><p>You might be wondering! What about the <strong>AppController</strong> in <strong>AppComponent, </strong>it is an external dependency that is required in the component.</p><ul><li>External Dependencies: Dependencies on which our <strong>AppModule</strong> itself is dependent on.</li><li>Our modules, now, are just lacking with the dependency of Context.</li><li>External Dependencies to our graph or module can be of Context, Activity, Service, etc.</li><li>They are external because <strong>WE NEVER CREATE CONTEXT / ACTIVITY / SERVICE INSTANCE BY NEW KEYWORD</strong>…</li></ul><h4>Modules with “includes” attribute</h4><p>Includes attribute: <strong>includes</strong> another module dependency to the current module So, my module’s @Module annotation got updated with includes attribute as:</p><blockquote>@Module(includes = [CommonModule::class])<br>abstract class ViewModelModule {</blockquote><blockquote>……</blockquote><blockquote>}</blockquote><p>Every time you call Component#build()</p><ul><li>Dagger by default creates new instances of every dependency to be injected.</li><li>Why Dagger doesn’t understand that I just need a single instance to be created for <strong>UserRepository</strong>?</li><li>How do we tell Dagger to create just a single instance for any dependency?</li><li>Limit the instances by Scope</li></ul><h4>Scope</h4><ul><li>Annotation informs Dagger to share the same instance every time Component.build() will be called.</li><li>It will make dependencies work as a Singleton for that particular Component</li></ul><h4>Named Annotations</h4><p>It may happen sometimes we need the objects of the same class with different reference. Typically, we need two types of Contexts: Application and Activity. But Dagger gets confused about which Context to use because it has got two modules that have methods that provide Context and it will throw an error on the build. How can we tell Dagger that this dependency should use Application Context or Activity Context?</p><p>We can have <strong>PresenterModule</strong> to provides Activity context and <strong>AppModule</strong> provides Application context. To identify which context we need at run time we can use <strong>NamedAnnotation </strong>as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d235e7c77e33e826c14a0a8f8e333054/href">https://medium.com/media/d235e7c77e33e826c14a0a8f8e333054/href</a></iframe><p>But in a large scale project naming the object by named annotation will be a tedious job. So alternatively we can define <strong>Qualifier </strong>which<strong> </strong>acts as the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0772c12c1019891f20dec4da8e071d6/href">https://medium.com/media/c0772c12c1019891f20dec4da8e071d6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6e9dbb879f1fb80dc565f7480a5e6fd/href">https://medium.com/media/d6e9dbb879f1fb80dc565f7480a5e6fd/href</a></iframe><p>In the next installment, we will look into scope and qualifiers more deeply and I’ll share more details of the dagger with example.</p><p>Here is the link for the example, which I am referencing in this post to explain components and modules.</p><p><a href="https://github.com/malikmotani/UnitTestSample-Kotlin-DSL">https://github.com/malikmotani/UnitTestSample-Kotlin-DSL</a></p><p>This might sound interesting. In this series, I’ll explain how to use <strong>Dagger</strong> in your project and make the maximum out of it with examples. So stay tuned for that, by the time keep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43be20c605b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/fastlane-to-dagger2-part-1-introduction-43be20c605b9">Fast Lane to Dagger2 Part — 1 : Introduction</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your apps fold; Make it work with foldable displays]]></title>
            <link>https://medium.com/mindful-engineering/make-your-apps-fold-make-it-work-with-foldable-displays-fe498263fce?source=rss-6d8dc69c056c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe498263fce</guid>
            <category><![CDATA[foldable-displays]]></category>
            <category><![CDATA[foldable-phone]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Malik Motani]]></dc:creator>
            <pubDate>Fri, 22 May 2020 10:42:33 GMT</pubDate>
            <atom:updated>2020-05-22T10:57:53.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InMxTwymP-iRKoammNMVWw.png" /></figure><p>Its been more than a year now since Google has announced the support for Foldable phones. A big hype was created when the first foldable smartphone was introduced. It creates new form factors for the unique experiences for consumers and new opportunities to drive innovations to the developers.</p><p>Foldable-phones are mainly focused on bigger screens and handy experience when folded (Cover display).</p><p>A large screen, richer and immersive experience, and multitasking with 2/3 multi-windows when unfolded (Main display) and smaller, less power-hungry display outside or it can be a part of the same display.</p><p>In this article we will talk about things that a developer needs to keep in mind while <a href="https://www.mindinventory.com/blog/how-to-develop-apps-for-foldable-smartphones/">developing an app for foldable devices</a>.</p><h3>Screen continuity</h3><p>Seamlessly continue what you are doing, after unfold or fold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*9fDjS8FcCoiQjcF7EzG1jQ.gif" /><figcaption>Android developers: <a href="https://developer.android.com/guide/topics/ui/foldables">Foldables</a></figcaption></figure><p>It&#39;s very important for a great user experience that whatever user interacting with on the cover display, should display the same content in a more interactive and informative way and dive deeper into their current task.</p><p>During the transition from the fold to unfold the app will receive the configuration change (Like we get in orientation change).</p><p>For this, the developer needs to make sure that the app properly supports <a href="https://developer.android.com/guide/topics/resources/runtime-changes">runtime configuration change</a>.</p><p>Unfolding triggers a configuration change for smallestScreenSize.screenLayout andscreenSize</p><p>Use of onSaveInstanceState and/or ViewModel to handle the data into changed configuration without restarting via handleConfigurationChange=&quot;&quot;</p><p>For the best experience declare resizeableActivity=true<strong> </strong>in the manifest.</p><h3>Multi-resume</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*HVlZU9H8Sa_n61duhQV5sw.png" /><figcaption>Android developers: <a href="https://developer.android.com/guide/topics/ui/foldables">Foldables</a></figcaption></figure><p>All the activities at the top in a multi-window need to be in resumed state for the user interaction. In Android Pie it was not shipped by google so it relied on the manufacturers to implement this optimization for foldables. But Android 10 onwards this feature is part of Android, so it is expected that we will get more of such devices and all our apps have to play nice :).</p><p>Till the Android Pie multi-window activity behavior needs to be changed for foldable devices since it can show 2/3 apps together.</p><p>For the Android Pie, Opt-in via a flag in the manifest</p><pre>&lt;meta-data<br>    android:name=&quot;android.allow_multiple_resumed_activities&quot; android:value=&quot;true&quot; /&gt;</pre><p>Note that more than one activity of the same app can be resumed at the same time it can happen that more than one activity from our app process, so be conscious about the libraries and the frameworks that might make the same functions.</p><h3>Multi-display</h3><p>Considering a foldable device, it can have 2 displays,</p><ol><li>Folded (Cover display)</li><li>Unfolded (Main display)</li></ol><p>From the Android 8.0 platform offers enhanced support for multiple displays. If an activity supports multi-window mode then the user can move this activity to one display to another display.</p><p>When an app launches an activity, we can specify which display the activity should run on. See <a href="https://developer.android.com/about/versions/oreo/android-8.0#mds">here</a> for the full documentation.</p><h3>Make your app resizable</h3><p>The UI should be designed in a way that it can handle multi-window mode and dynamic resizing. We can do it by defining resizeableActivity=true it in the manifest. We can test our app&#39;s behavior in split-screen or with a <a href="https://developer.android.com/guide/topics/ui/foldables#emulators">Foldable emulator</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61--BVXoMDIPUsB6hx58hg.png" /><figcaption>Android developers: <a href="https://developer.android.com/guide/topics/ui/foldables">Foldables</a></figcaption></figure><p>If our app sets resizeableActivity=false, this tells the system that it doesn&#39;t support multi-window. The system will try to resize your app or put it in multi-window mode, but compatibility is implemented by applying the same configuration to all the components in the app (including all of its Activities, Services, and more). In some cases, major changes (like a display size change) might restart activities!</p><h3><strong>How to test your app for foldable smartphones?</strong></h3><p>You can use the foldable emulator provided by Samsung to test your app in a foldable environment or you can use Android Emulator too.</p><p>That’s it for now, feel free to share your thoughts on foldable displays and what innovations can be done with foldable devices, We will be coming up with another blog on this soon with more technical detail, So stay with us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe498263fce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/make-your-apps-fold-make-it-work-with-foldable-displays-fe498263fce">Make your apps fold; Make it work with foldable displays</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into Kotlin DSL Part-3: Unit testing with Kotlin DSL in Android]]></title>
            <link>https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-3-unit-testing-with-kotlin-dsl-in-android-8119d93fc4b7?source=rss-6d8dc69c056c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8119d93fc4b7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-dsl]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Malik Motani]]></dc:creator>
            <pubDate>Wed, 11 Mar 2020 15:20:10 GMT</pubDate>
            <atom:updated>2020-03-11T15:20:10.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjRI90fPTExXB_Nq-Sd6fQ.jpeg" /><figcaption>Unsplash: <a href="https://unsplash.com/@laurieannerobert">Laurie-Anne Robert</a></figcaption></figure><p>In Android, <a href="https://developer.android.com/training/testing/unit-testing/local-unit-tests"><strong>JUnit</strong></a> and <a href="https://site.mockito.org/"><strong>Mockito</strong></a> are used most often for local unit tests. If you are one of them who don’t prefer to write unit test of your code, I strongly recommend you to write unit tests to avoid issues in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*PutPebVSc1-rhWUTdWrbqg.gif" /><figcaption>Giphy: <a href="https://giphy.com/gifs/loop-opening-closing-EPR5sgG0y4SaY">Loop Closing GIF</a></figcaption></figure><p>In case you don’t know what Kotlin DSL is all about, I’ll recommend you to read previous blogs of this series to get a basic idea about the Kotlin DSL</p><p><a href="https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-1-getting-started-945c00ce5369">Diving into Kotlin DSL Part-1: Getting started</a></p><p>and to set up Kotlin DSL with Android studio</p><p><a href="https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-2-kotlin-enters-the-gradle-realm-effb24e48fa8">Diving into Kotlin DSL Part-2: Kotlin enters the Gradle realm</a></p><p>Now if you have done that, let&#39;s get started with Android unit testing.</p><p>Before diving into the details of unit tests, I assume you already know a few basic things regarding unit tests, like how to use JUnit and Mockito. Still, I’ll try to make it easy for you to understand. There are certain steps to write a local unit test.</p><h3><strong>Step 1: Set up your testing environment</strong></h3><p>Initially, it requires few dependencies since we have already set up DSL in our previous blog we will add dependencies in our <strong>“Dependencies.kt”</strong> file then we will use its reference in <strong>build.gradle.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc540af75f86e8cc47807691f51fefdd/href">https://medium.com/media/dc540af75f86e8cc47807691f51fefdd/href</a></iframe><p>Here I have added required libraries for unit testing in Dependencies.kt. You can ignore <strong>daggerMock </strong>if you are not using <strong>Dagger</strong>. You can try this library which has useful kotlin extension, I found it handy while using Mockito.</p><pre>&quot;com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0&quot;</pre><p>Now, we will add these dependencies in build.gradle</p><pre>dependencies {<br>    .....</pre><pre>    //unittest<br>    testImplementation TestLibs.junit<br>    androidTestImplementation TestLibs.testRunner</pre><pre>    testImplementation UnitTest.kotlinTest     <br>    testImplementation UnitTest.mockitoCore     <br>    testImplementation UnitTest.mockitoKotlin     <br>    testImplementation UnitTest.mockitoInline<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb5b2e7a2a2fb087cfcb467fffedf3a2/href">https://medium.com/media/eb5b2e7a2a2fb087cfcb467fffedf3a2/href</a></iframe><h3><strong>Step 2: Create a local unit test class</strong></h3><p>Create a class underhood the <strong>app/build/src/test </strong>directory according to your packages.</p><p>To better understanding, I have created a sample app which has a ViewModel named as <strong>RandomUserViewModel.</strong></p><p><a href="https://github.com/malikmotani/UnitTestSample-Kotlin-DSL">malikmotani/UnitTestSample-Kotlin-DSL</a></p><p>Here is our ViewModel app/src/main/java/com/unittestsample/app/presentation/user/RandomUserViewModel.kt</p><p>So now we will be writing the test cases for RandomUserViewModel. To create unit test, here I have created a class</p><p>app/src/test/java/com/unittestsample/app/presentation/user/RandomUserViewModelUnitTestNew.kt</p><p>and</p><p>app/src/test/java/com/unittestsample/app/presentation/user/RandomUserViewModelUnitTestOld.kt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*OYmNn2Xnw8PH5tIAv0FNgA.gif" /><figcaption>Giphy: <a href="https://giphy.com/gifs/alanwalker-alan-walker-3oKIP9uJqdNt9jRrCU">Curious The Matrix GIF By Alan Walker</a></figcaption></figure><p>You might be wondering why I have created two classes here? No need to worry, I have created two classes just to explain the old method of unit testing and a new approach which is also known as Kotlin style of unit testing. I recommend if you are writing new test cases follow the approach which is written in <strong>RandomUserViewModelUnitTestNew.kt</strong></p><h3><strong>Step 3: Mock the dependencies</strong></h3><p>Now we have a class where we can write a test case. Here in our <strong>RandomUserViewModel</strong> has one method <strong>fetchRandomUsers() </strong>which needs to be unit tested.</p><p>To start writing a unit test of our ViewModel we need an object of RandomUserViewModel and it needs <strong>RandomUserUseCase</strong> instance as an argument in its constructor.</p><p>So here we will create a mock object of <strong>RandomUserUseCase w</strong>hich helps us to create an object of <strong>RandomUserViewModel.</strong></p><p>In addition to that, we have an observer which observers the events published by our live data, so we need a mock object of our observer too. And we also need some predefined values which we can expect as output when our unit test finishes its execution.</p><pre>//output value    <br>private val successLoginResponse: Resource&lt;ArrayList&lt;User&gt;&gt; =        Resource(Status.SUCCESS, randomUserResponse().data)    </pre><pre>private val errorLoginResponse: Resource&lt;Throwable&gt; =        Resource(Status.ERROR, throwable = Exception())     </pre><pre>//mock dependencies    <br>private val randomUserUseCase = mock&lt;RandomUserUseCase&gt;()    </pre><pre>private val randomUserViewModel by lazy { RandomUserViewModel(randomUserUseCase) }    </pre><pre>private var randomUserObserver = mock&lt;Observer&lt;Resource&lt;ArrayList&lt;User&gt;&gt;&gt;&gt;()</pre><h3><strong>Step 4: Stubbing</strong></h3><p>Now, we have a method to test, which gets the data from an asynchronous data source (here web API).</p><p>For a quick note unit tests never performs an actual data fetching, so we have to provide the data when any asynchronous operation takes place, this is called stubbing.</p><p>Here we will provide a dummy response when our API will get a call from our unit test. We will test two scenarios, success and failure so we have written two stubbings which can be used for different scenarios.</p><pre>private fun stubFetchRandomUserSuccess() {        <br>    whenever(            <br>       randomUserUseCase.execute()        <br>    ).thenReturn( <br>       Single.just(randomUserResponse())  <br>    )<br>}     </pre><pre>private fun stubFetchRandomUserError() {        <br>    whenever( <br>       randomUserUseCase.execute()       <br>    ).thenReturn( <br>       Single.error(Throwable())        <br>    )<br>}</pre><h3><strong>Step 5: Execution</strong></h3><p>As a final step, we will write the test case itself. Set an observer first on the live data object and execute the method that we want to test. In our case <strong>fetchRandomUsers() </strong>is a private method which is called inside <strong>loadPage() </strong>so we will call loadPage() method in order to test our actual method.</p><p>Now we will observe the response and if it matched with our expected response that our case is tested successfully.</p><p>Here I have added success and failure cases, it may need more cases to be tested as per different scenarios.</p><p>That’s it for now, feel free to share your review and let us know if you need separate series on Dagger2 in comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8119d93fc4b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-3-unit-testing-with-kotlin-dsl-in-android-8119d93fc4b7">Diving into Kotlin DSL Part-3: Unit testing with Kotlin DSL in Android</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into Kotlin DSL Part-2: Kotlin enters the Gradle realm]]></title>
            <link>https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-2-kotlin-enters-the-gradle-realm-effb24e48fa8?source=rss-6d8dc69c056c------2</link>
            <guid isPermaLink="false">https://medium.com/p/effb24e48fa8</guid>
            <category><![CDATA[gradle-kotlin-dsl]]></category>
            <category><![CDATA[kotlin-dsl]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Malik Motani]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 10:56:55 GMT</pubDate>
            <atom:updated>2020-01-18T06:50:57.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXdd3HxWDROjhURbEznx3w.jpeg" /><figcaption>Unsplash : <a href="https://unsplash.com/@artemverbo">Artem Verbo</a></figcaption></figure><p>If you are one of them who doesn’t like how you write stuff in build.gradle, stay tuned you have come to the right place.</p><p>Groovy is widely used in <a href="https://www.mindinventory.com/android-application-development.php">Android app development</a> for the usual building process and its customization. Some of the tasks are performed by Android Studio configuration and we can also write our own gradle tasks.</p><p>I belong to the community who doesn’t have much knowledge about groovy and feels <strong>yaaaak</strong> when anything requires to code in groovy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*AFzGVmalaPNcy0vBtSIFgQ.gif" /><figcaption>Giphy: <a href="https://giphy.com/gifs/mad-ugh-unhappy-Cc33x00kRXRlu">Angry Hate GIF</a></figcaption></figure><p>Here Kotlin DSL will become a lifesaver. Most interestingly it will allow us to write code in Kotlin, which will perform all the gradle tasks. Additionally, all the third-party dependencies (Libraries we use most often, you know what I mean :D) can be managed with Kotlin itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*BaYYOW8nOwT_u6kvCkPQtQ.gif" /><figcaption>Giphy : <a href="https://giphy.com/gifs/911onFOX-911-ryan-murphy-9-1-1-2m1ljfEYgaOpfp5N7M">Lifesaver GIF</a></figcaption></figure><p>You might be wondering what is <strong>Kotlin DSL</strong>? I will recommend you to read the first blog from this series to get a basic idea of Kotlin DSL</p><p><a href="https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-1-getting-started-945c00ce5369">Diving into Kotlin DSL Part-1: Getting started</a></p><p>Now if you have done that already we can dive deep into the world of Kotlin DSL.</p><p>There are few steps by which you can set up DSL with your Android Studio:</p><h3><strong>Step 1: Create “buildSrc” directory</strong></h3><p>Android Studio automatically creates app level and module level build.gradle files to handle project level and module level dependencies.</p><p>Now, we are going to manage every dependency in a way, so that it will be accessible from a single place. Don’t worry if you have modularization in your project, even multiple modules can be configured with this mechanism.</p><p>Sometimes you might have faced two different versions of the same library that have been used in multiple modules and that creates inconstancy problems. By this method, we can have the same version of the library available to all the modules.</p><p>First, create <strong>buildSrc </strong>directory<strong> </strong>in the root directory of your project. This will provide a gradle feature that enables us to define tasks and access tools that can be used for the build scripts. By adding <strong>kotlin-dsl </strong>plugin in the build config, we can use Kotlin within this directory.</p><p>For more information check the Gradle documentation<em> </em>for <strong>buildSrc</strong><em> </em><a href="https://docs.gradle.org/current/userguide/organizing_gradle_projects.html#sec:build_sources"><em>here</em></a></p><p>Now let’s create the following files inside <strong>buildSrc </strong>directory in the package structure as shown in the image below:</p><ol><li>build.gradle.kts</li><li>Dependencies.kt (Inside src/main/kotlin package)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*J3DEewDJohP101xi7Klu2w.png" /></figure><h3><strong>Step 2: Apply “kotlin-dsl” plugin in build.gradle.kts</strong></h3><p>Here I have supplied <strong>buildSrc </strong>by which we can get this plugin from the repository.</p><p>using .kts extension will let Gradle know that this file is a Kotlin script and not a Groovy one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdd1e96b7a26e82d192b6387189aaca5/href">https://medium.com/media/cdd1e96b7a26e82d192b6387189aaca5/href</a></iframe><h3><strong>Step 3: Add values to Dependencies.kt</strong></h3><p>Above is Kotlin’s file which has singleton classes to define dependencies used throughout the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc540af75f86e8cc47807691f51fefdd/href">https://medium.com/media/dc540af75f86e8cc47807691f51fefdd/href</a></iframe><p>In this way, we can define all the dependencies easily and in a more readable manner at a single place.</p><h3><strong>Step 4: Convert build.gradle files and update with values from Dependencies.kt</strong></h3><p>Update the project level <strong>build.gradle </strong>file with classpath inside the dependencies block with the values from <strong>“Dependencies.kt”</strong> and convert the Gradle <em>clean</em> task to Kotlin syntax. Now the updated file will look like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa7d639b25815323054a62b9ba685a3/href">https://medium.com/media/4fa7d639b25815323054a62b9ba685a3/href</a></iframe><p>Similarly, update app level <strong>build.gradle</strong> values from <strong>“Dependencies.kt”</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb5b2e7a2a2fb087cfcb467fffedf3a2/href">https://medium.com/media/eb5b2e7a2a2fb087cfcb467fffedf3a2/href</a></iframe><p>Now, its time for magic!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*1aOosg-nk3gyuqSuPPSLnA.gif" /><figcaption>Giphy: <a href="https://giphy.com/gifs/syfy-the-magicians-3oEjHJjKXmbFBY42WI">The Magicians Magic GIF By SYFY</a></figcaption></figure><p>You will start getting suggestions while writing dependencies.</p><p>That’s it! Now your configuration is ready to use. I’ll keep exploring this series by the time feel free to share your view on Kotlin DSL in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=effb24e48fa8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/diving-into-kotlin-dsl-part-2-kotlin-enters-the-gradle-realm-effb24e48fa8">Diving into Kotlin DSL Part-2: Kotlin enters the Gradle realm</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saying Hello to Jetpack Compose]]></title>
            <link>https://medium.com/mindful-engineering/saying-hello-to-jetpack-compose-a96d9e9c4f77?source=rss-6d8dc69c056c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96d9e9c4f77</guid>
            <category><![CDATA[android-jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Malik Motani]]></dc:creator>
            <pubDate>Sat, 05 Oct 2019 12:06:14 GMT</pubDate>
            <atom:updated>2021-09-01T12:06:44.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lafsw3V7hxw2jE3Zmaojbw.png" /></figure><p>Jetpack compose is still in labs(<em>Pre-alpha), </em>Let’s find out if we can compose anything with Jetpack compose or not.</p><p>If you remember the time when Kotlin was newly introduced and we were into our Java zone, in a short period of time Kotlin became the <a href="https://techcrunch.com/2017/05/17/google-makes-kotlin-a-first-class-language-for-writing-android-apps/">first-class language</a> for Android app development</p><p>The same thing may apply to Jetpack Compose because it is the first time when Google is taking a major step for native android app development towards <strong>declarative UI approach</strong>. Although it is not the first attempt for the <strong>declarative UI approach</strong>, Facebook has already developed <a href="https://fblitho.com/">Litho</a> and in Kotlin Anko, <a href="https://github.com/Kotlin/anko/wiki/Anko-Layouts">Anko layouts</a> is already there, but when something comes from the Android Team it self, we got to try it, isn’t it?</p><h3><strong>Idea of Jetpack compose</strong></h3><p>It’s declarative UI toolkit build for Android. It is inspired by React, Litho, Vue.js and Flutter and completely written in Kotlin and it is fully compatible with existing current Android view system. It aims to make your android view hierarchy more declarative.</p><p>With Compose, UI is defined as composable functions and this function transforms data into view hierarchy.</p><h3><strong>What is compose?</strong></h3><ul><li><strong>A new set of Jetpack UI widgets:</strong> Not views or fragments they are something smaller, modular and easy to work with.</li><li><strong>A kotlin compiler plugin:</strong> It makes easy to define our own composable widgets</li><li><strong>Fully compatible with the existing view system</strong></li><li><strong>Experimental</strong></li></ul><h4><strong>Core principles</strong></h4><ol><li><strong>Concise and Idiomatic Kotlin: </strong>Built with the benefits that Kotlin brings</li><li><strong>Declarative: </strong>Fully declarative for defining UI components, including drawing and creating custom layouts</li><li><strong>Compatible:</strong> Compatible with existing views</li><li><strong>Enable Beautiful Apps: </strong>Designed with Material Design out of the box and animations from the start</li><li><strong>Accelerate Development: </strong>Accelerate development by writing less code and using tools</li></ol><h4><strong>UI as a function</strong></h4><p>In Jetpack Compose we got to write Composable Functions to create our UI</p><pre>@Composable<br>fun Welcome(name : String){<br>    Text(“Welcome $name”)<br>}</pre><ul><li>Take data as input</li><li>Emit the view hierarchy when invoked</li></ul><p>It can be directly used with <strong>setContent</strong> within our Activity.</p><h3><strong>Setup</strong></h3><p>Since Jetpack compose is in Developer Preview, It is not available as the same old gradle dependency for the Stable version of Android Studio just yet, Either you got to Download Android Studio Canary build<em>(4.0 Canary 1 while writing)</em> from <a href="https://developer.android.com/studio/preview/index.html">here</a>, or you can download the source code to use it from <a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/compose/">here</a>, and guess what? the second option is what we are going to try today.</p><h4><strong>Step 1: First, we need to install the Repo tool (if it has not been installed already)</strong></h4><pre>mkdir bin PATH=~/bin:$PATH curl https://storage.googleapis.com/git-repo-downloads/repo &gt; ~/bin/repo </pre><pre>chmod a+x ~/bin/repo</pre><p>Once done check repo status using the following command</p><pre>repo status</pre><h4><strong>Step 2: Create a directory let’s say “JetpackCompose”</strong></h4><pre>mkdir ~/JetpackCompose</pre><pre>cd ~/JetpackCompose</pre><p>and setup git config like (if not setup)</p><pre>git config — global user.name “Your name”</pre><pre>git config — global user.email “you@example.com”</pre><p>Now initialise repo</p><pre>repo init -u https://android.googlesource.com/platform/manifest -b androidx-master-dev</pre><p>Repo has been initialised now and if we check <strong>JetpackCompose </strong>directory there will be ”<strong>.repo</strong>” listing</p><p>Now hit the below command</p><pre>ls -a ~/JetpackCompose/.repo</pre><p>As per Android docs: <strong>Now your repository is set to pull only what you need for building and running AndroidX libraries. Download the code (and grab a coffee while we pull down 6 GB)</strong></p><h4><strong>Step 3: Download the source</strong></h4><pre>repo sync -j8 -c</pre><p>It will take a while to download, when it is successfully downloaded, we are ready to start.</p><pre>cd ~/JetpackCompose/frameworks/support/ui</pre><pre>./studiow</pre><p>This will start with Android studio, and it will show compose source.</p><p><strong>Note: While using compose it is required to start Android studio from this directory only.</strong></p><p>Accept the licence and we are ready to compose our UI.</p><p><strong>Create an Activity to setup UI in @Composable method</strong></p><pre>class MainActivity : AppCompatActivity() {</pre><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>        setContent {<br>            loadUi()<br>        }<br>    }</pre><pre>    @Composable<br>    fun loadUi() {<br>        CraneWrapper {<br>            MaterialTheme {<br>                Text(<br>                  text = &quot;Hello world!&quot;,<br>                  // apply theme as per requirement                    <br>                 style = TextStyle(<br>                    color = Color.Blue,<br>                    fontSize = +withDensity { 50.dp.toPx().value }), <br>                    textAlign = TextAlign.Center<br>                )<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*arMJlW6T4uQ1oUcqaIWzTw.png" /></figure><p>Look into the next blog ‘<a href="https://medium.com/mindful-engineering/how-to-create-simple-ui-with-jetpack-compose-part-ii-1c14148b7ffe?source=friends_link&amp;sk=403638c766c7c49cf70e787bb67f5e29">How to create realistic UI with Jetpack Compose’</a> for more details with real-time examples.<br>I’ll be continuing this as a series of blogs, In the upcoming blogs, we will play with <strong>Composable</strong> functions and create some real-world UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96d9e9c4f77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/saying-hello-to-jetpack-compose-a96d9e9c4f77">Saying Hello to Jetpack Compose</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>