<?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 Aung Thiha on Medium]]></title>
        <description><![CDATA[Stories by Aung Thiha on Medium]]></description>
        <link>https://medium.com/@AungThiha3?source=rss-a9a6422dc570------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xJwJr3ikr-5WFAI8nIdCyQ.jpeg</url>
            <title>Stories by Aung Thiha on Medium</title>
            <link>https://medium.com/@AungThiha3?source=rss-a9a6422dc570------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:10:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AungThiha3/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[Kotlin Constants in Android: Top-level vs. Companion-enclosed]]></title>
            <link>https://proandroiddev.com/top-level-constants-vs-companion-enclosed-constants-using-kotlin-in-android-cbb067732428?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb067732428</guid>
            <category><![CDATA[bytecode]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 00:47:35 GMT</pubDate>
            <atom:updated>2025-02-06T03:44:01.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RtGlTLdx4Qffsl8M" /><figcaption>Photo by <a href="https://unsplash.com/@louis993546?utm_source=medium&amp;utm_medium=referral">Louis Tsai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>We often declare Kotlin constants in Android without giving them a second thought. Some use top-level constants while others wrap them inside a companion object. But does this choice affect performance, APK size, or memory usage? Let’s break it down by diving into the bytecode and R8 optimizations.</p><h3>Preparing the Code</h3><pre>const val TOP_LEVEL_CONSTANT = &quot;TOP_LEVEL_CONSTANT&quot;<br><br>class MainActivity : ComponentActivity() {<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        println(TOP_LEVEL_CONSTANT)<br>        println(COMPANION_ENCLOSED_CONSTANT)<br>    }<br><br>    companion object {<br>        const val COMPANION_ENCLOSED_CONSTANT = &quot;COMPANION_ENCLOSED_CONSTANT&quot;<br>    }<br>}</pre><p>We have top-level constant at the top and a companion object containing a constant at the bottom of MainActivity. The constants are used in onCreate.</p><h3>Decompiling the Class With Android Studio</h3><p>To get the Java bytecode, we’ll simply go to the Tools menu in Android Studio -&gt; Kotlin -&gt; Show Kotlin Bytecode. A new pane showing Java bytecode will appear on the right.</p><p>Since reading Java bytecode directly is complex, we’ll click the Decompile button in the pane to get a Java representation.</p><pre>public final class MainActivity extends ComponentActivity {<br>   @NotNull<br>   public static final Companion Companion = new Companion((DefaultConstructorMarker)null);<br>   @NotNull<br>   public static final String COMPANION_ENCLOSED_CONSTANT = &quot;COMPANION_ENCLOSED_CONSTANT&quot;;<br><br>   protected void onCreate(@Nullable Bundle savedInstanceState) {<br>      super.onCreate(savedInstanceState);<br>      String var2 = &quot;TOP_LEVEL_CONSTANT&quot;;<br>      System.out.println(var2);<br>      var2 = &quot;COMPANION_ENCLOSED_CONSTANT&quot;;<br>      System.out.println(var2);<br>   }<br><br>   public static final class Companion {<br>      private Companion() {<br>      }<br><br>      public Companion(DefaultConstructorMarker $constructor_marker) {<br>         this();<br>      }<br>   }<br>}<br><br>public final class MainActivityKt {<br>   @NotNull<br>   public static final String TOP_LEVEL_CONSTANT = &quot;TOP_LEVEL_CONSTANT&quot;;<br>}</pre><p>I removed the parts that aren’t relevant to our discussion to make it easy to read. Let’s break down the relevant parts.</p><pre>  protected void onCreate(@Nullable Bundle savedInstanceState) {<br>      super.onCreate(savedInstanceState);<br>      String var2 = &quot;TOP_LEVEL_CONSTANT&quot;;<br>      System.out.println(var2);<br>      var2 = &quot;COMPANION_ENCLOSED_CONSTANT&quot;;<br>      System.out.println(var2);<br>   }</pre><p>Inside the onCreate method, we can see that the constants are inlined and that’s great.</p><pre>public final class MainActivityKt {<br>   @NotNull<br>   public static final String TOP_LEVEL_CONSTANT = &quot;TOP_LEVEL_CONSTANT&quot;;<br>}</pre><p>However, now we end up with a redundant MainActivityKt class that isn’t even used. This comes from the top-level constant and it increases the app size.</p><pre>public final class MainActivity extends ComponentActivity {<br>   @NotNull<br>   public static final Companion Companion = new Companion((DefaultConstructorMarker)null);<br>   @NotNull<br>   public static final String COMPANION_ENCLOSED_CONSTANT = &quot;COMPANION_ENCLOSED_CONSTANT&quot;;<br><br>   ...<br><br>   public static final class Companion {<br>      private Companion() {<br>      }<br><br>      public Companion(DefaultConstructorMarker $constructor_marker) {<br>         this();<br>      }<br>   }<br>}</pre><p>With a companion-enclosed constant, it’s even worse. The companion object becomes a static inner class which gets instantiated during the outer class loading and assigned to a static field. This introduces unnecessary object creation and memory overhead.</p><h3>Relevance of D8 and R8</h3><p>It’s important to note that the Java code we looked at came from Java bytecode and Android does not run Java bytecode. The Java bytecode still needs to go through a dex compiler called D8 to turn into Dalvik bytecode that Android can run [1][2]. More importantly, our code hasn’t gone through R8 optimization yet. R8 optimization will remove unused code [3].</p><blockquote>Code shrinking (also known as tree shaking), is the process of removing code that R8 determines is not required at runtime. This process can greatly reduce your app’s size if, for example, your app includes many library dependencies but utilizes only a small part of their functionality.</blockquote><p>So, to apply R8, we can enable it in the project-level Gradle file (also known as root-level Gradle file).</p><pre>isMinifyEnabled = true</pre><p>Next, we go to the Build menu of the Android Studio -&gt; Build APK(s) to build an APK that contains Dalvik bytecode.</p><h3>Decompiling the APK With Apktool and Jadx</h3><p>Now that we got our APK ready, let’s see what happens when D8 and R8 are involved in the compilation process.</p><p>So, to get the Dalvik bytecode from the APK, we’ll use <a href="https://apktool.org/">apktool</a> [4].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*KQ0X_3RRCVkvHVolGc4UZw.png" /><figcaption>Decompiled Dalvik Bytecode</figcaption></figure><p>We get these two files. Let’s see what’s inside each of them but first, to simplify our analysis, we need to translate the Dalvik bytecode into Java representation. (If you wanna check the Dalvik bytecode, I’ve posted them <a href="https://gist.github.com/AungThiha/6e7de0cb845890f24b396c7c3e5f22f9">here</a>.)</p><p>The easiest way to get the Java representation from smali files is to use <a href="https://github.com/skylot/jadx">jadx</a> [5].</p><pre>public final class MainActivity$Companion {<br>    public /* synthetic */ MainActivity$Companion(DefaultConstructorMarker defaultConstructorMarker) {<br>        this();<br>    }<br><br>    private MainActivity$Companion() {<br>    }<br>}</pre><p>This is what we get for MainActivity$Companion.smali.</p><p>Looking at the code, we now know that R8 doesn’t remove the static inner class derived from the companion object but what happened to MainActivityKt that comes from the top-level constant? Let’s look into MainActivity.smali to find out.</p><pre>public final class MainActivity extends ComponentActivity {<br>    public static final Companion Companion = new Companion((DefaultConstructorMarker) null);<br><br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        System.out.println((Object) &quot;TOP_LEVEL_CONSTANT&quot;);<br>        System.out.println((Object) &quot;COMPANION_ENCLOSED_CONSTANT&quot;);<br>    }<br>}</pre><p>MainActivityKt is not here either, so we can conclude that R8 removes it. This happens because nothing references MainActivityKt. So, R8 knows it’s unused. As for the static inner class derived from the companion object, because it’s referenced by MainActivity, R8 doesn’t remove it.</p><h4><strong>Disclaimer:</strong></h4><ul><li>please, note that different decompiler decompiles APKs differently. If you use jadx directly on the APK, it’ll remove the static inner class derived from the companion object too. This can make you think R8 removes it but the fact that apktool can still get it means it’s in the APK.</li><li>I used Android Gradle Plugin 8.8.0. Different Android Gradle Plugins use different R8 versions and this may affect the result.</li></ul><h3>Sharing Constants Across Different Classes</h3><p>Sometimes, you might wanna share the constants across different classes. For that, we can declare top-level constants in a dedicated file, now that we know classes generated for enclosing only constants are removed by R8 because they’re not referenced by any classes after the constants are inlined.</p><h3>Grouping Multiple Constants for Readability</h3><p>Sometimes, keeping all constants at one level is not enough. Sometimes, you might wanna group them for readability. Let’s see if grouping with singleton objects is a viable option.</p><pre>object MyConstants {<br><br>    const val FIRST_LEVEL = &quot;FIRST_LEVEL&quot;<br><br>    object NestConstants {<br>        const val SECOND_LEVEL = &quot;SECOND_LEVEL&quot;<br>    }<br>}</pre><p>So, we create the MyConstants class and simply print the constants in MainActivity.</p><p>We’ll also create HelloActivity, declare it in the manifest and make it use FIRST_LEVEL and SECOND_LEVEL. (I’ll leave out the code for HelloActivity to keep the article short.)</p><p>Then, we’ll build the APK and use apktool to decompile it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1mAxJ39SxmlafmmgfjPG5A.png" /><figcaption>Decompiled Dalvik Bytecode After Adding MyConstants</figcaption></figure><p>This is all we get. MyConstants is gone. R8 can remove it for the same reason it can remove MainActivityKt. It’s because after inlining the constants from that class, the class is no longer referenced by any other class which helps R8 know it’s not used. (If you still wanna take a look at the smali files, I’ve posted them <a href="https://gist.github.com/AungThiha/aff23d3ce95c90c04af533fb9e786acd">here</a>.)</p><h3>Conclusion</h3><ul><li><strong>Companion-enclosed Constants:</strong> Avoid them, as they generate redundant static inner class that introduces unnecessary object creation and memory overhead.</li><li><strong>Top-level Constants</strong>: Best for single-file usage.</li><li><strong>Shared Constants Across Multiple Classes:</strong> Use a dedicated file with top-level constants.</li><li><strong>Grouped Constants</strong>: Use singleton objects.</li><li><strong>R8 Optimization:</strong> Always enable isMinifyEnabled for production builds to benefit from code shrinking. R8 removes the enclosing classes of top-level, shared, and grouped constants because the classes are no longer referenced after the constants are inlined.</li></ul><p>Happy coding, everyone!</p><h3>References</h3><ol><li><a href="https://source.android.com/docs/core/runtime">https://source.android.com/docs/core/runtime</a> [Accessed on: 6 Feb 2025]</li><li><a href="https://developer.android.com/tools/d8">https://developer.android.com/tools/d8</a> [Accessed on: 6 Feb 2025]</li><li><a href="https://developer.android.com/build/shrink-code">https://developer.android.com/build/shrink-code</a> [Accessed on: 6 Feb 2025]</li><li><a href="https://apktool.org/">https://apktool.org/</a> [Accessed on: 6 Feb 2025]</li><li><a href="https://github.com/skylot/jadx">https://github.com/skylot/jadx</a> [Accessed on: 6 Feb 2025]</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb067732428" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/top-level-constants-vs-companion-enclosed-constants-using-kotlin-in-android-cbb067732428">Kotlin Constants in Android: Top-level vs. Companion-enclosed</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[Jetpack Compose: Assert Intent Data Consumption in Instrumented Tests]]></title>
            <link>https://proandroiddev.com/jetpack-compose-assert-intent-data-consumption-in-instrumented-tests-5c999d42aee8?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c999d42aee8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 02:12:25 GMT</pubDate>
            <atom:updated>2023-12-09T19:36:44.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BFmXLpcFiKyMZmgQVo2Yg.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/turned-on-android-smartphone-t8TOMKe6xZU">https://unsplash.com/photos/turned-on-android-smartphone-t8TOMKe6xZU</a></figcaption></figure><p>Before we talk about how to assert intent data consumption in instrumented tests, we need to talk about why it’s crucial.</p><p>Consider a scenario where your composables access an intent extra. You might wanna verify that your composables can display the value coming from the intent correctly.</p><pre>val text = intent.getStringExtra(Intent.EXTRA_TEXT) ?: &quot;no extra text&quot;<br>Text(name = text)</pre><p>What’s more likely to happen in real-world scenarios is that your Activity will access the intent extras, pass them over to ViewModel and ViewModel will compute based on the input and set the UI state.</p><p>The question is, how do we assert that the intent extras are consumed correctly if we wanna avoid the high cost of manual testing?</p><p>If you Google for a solution, ComposeTestRule, provided by Jetpack, is most likely the first thing you’ll find. There are two main ways to create a ComposeTestRule: createComposeRule and createAndroidComposeRule.</p><p>createAndroidComposeRule is the tool of choice if you want to launch your own Activity, but createAndroidComposeRule takes only two parameters, as you can see in the screenshot below taken from <a href="https://github.com/androidx/androidx/blob/androidx-main/compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/AndroidComposeTestRule.android.kt#L127">the Jetpack’s official Compose test library</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNz6cQjioJ9aKUWy7KeUaA.png" /><figcaption>A Function From Official Compose Test Library</figcaption></figure><p>This means there’s no straightforward way to launch an Activity with your own intent using the tools provided by Jetpack in order to assert composables in the Activity.</p><p>That’s the problem <a href="https://github.com/AungThiha/ComposeUiTest">ComposeUiTest</a> solves. This library uses the official Compose test library under the hood and provides easy-to-use functions for developer friendliness.</p><p>Let’s take a look at how easy it is to use the library.</p><p>First, import the library.</p><pre>dependencies {<br>    androidTestImplementation(&quot;io.github.aungthiha:compose-ui-test:1.0.1&quot;)<br>}</pre><p>In your test case, you can pass in your intent to start an Activity and in the trailing lambda, you can assert your composables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61a1bb741ea19f629bd573483e234a73/href">https://medium.com/media/61a1bb741ea19f629bd573483e234a73/href</a></iframe><p>You can also directly use ActivityScenario to launch an Activity the way you prefer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbdf153b5566947bb05d1b8b1fa87e2/href">https://medium.com/media/5dbdf153b5566947bb05d1b8b1fa87e2/href</a></iframe><p>But wait, what if you need to start all test cases with the same intent? Repeating runAndroidComposeUiTest in all the test cases would be cumbersome. For that, we can create a test rule using createAndroidComposeRule. Yes, it’s the same function name as the official function but it comes from the library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf762ab4f10957f9fdedd4f81a93889/href">https://medium.com/media/dcf762ab4f10957f9fdedd4f81a93889/href</a></iframe><p>That’s all there is! That’s how easy it is to use the library.</p><p>Curious how the library internally works?</p><p>The runAndroidComposeUiTest function is written by referencing its counterpart from the Jetpack’s official Compose test library.</p><p>In a nutshell, the runAndroidComposeUiTest utilizes AndroidComposeUiTestEnvironment to run the test and provide AndroidComposeUiTest to the trailing lambda(block) to perform assertions on composables. AndroidComposeUiTestEnvironment does not hold reference to the Activity; instead, it uses the ActivityScenario created by the parameter activityLauncher to retrieve the Activity instance whenever it needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402e6c5a892cdf1a287affe9f71353ce/href">https://medium.com/media/402e6c5a892cdf1a287affe9f71353ce/href</a></iframe><p>The overloaded runAndroidComposeUiTest that takes in an intent uses the one that takes in activityLauncher internally, which is explained above.</p><p>As for createAndroidComposeTestRule, it initializes an instance of AndroidComposeTestRule using an ActivityScenarioRule created with the provided intent. It returns the initialized AndroidComposeTestRule instance, which is then available for use in performing assertions on composables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1e90b0fb9251b4672dab383b937b205/href">https://medium.com/media/e1e90b0fb9251b4672dab383b937b205/href</a></iframe><p>The library hides all of these details from developers, allowing them to concentrate on writing the actual test cases.</p><p>If you find this article and the library valuable, a round of applause would be much appreciated. Please, feel free to leave a comment if anything needs clarification or if you have additional insights. Your feedback fuels my commitment to enhancing my blogging skills and supporting fellow developers.</p><p>I hope you enjoyed the article! Happy coding!</p><p><a href="https://github.com/AungThiha/ComposeUiTest">GitHub - AungThiha/ComposeUiTest: A tool to launch an activity with intent in instrumented test and assert composables in the activity, solving the limitation of ComposeTestRule that does not accept an intent as an input for launching activities.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c999d42aee8" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jetpack-compose-assert-intent-data-consumption-in-instrumented-tests-5c999d42aee8">Jetpack Compose: Assert Intent Data Consumption in Instrumented Tests</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[Live Template for Writing Composable Functions]]></title>
            <link>https://medium.com/@AungThiha3/android-composable-template-ef9db6615ea3?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef9db6615ea3</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 10:23:30 GMT</pubDate>
            <atom:updated>2023-12-05T10:10:08.689Z</atom:updated>
            <content:encoded><![CDATA[<p>I think every Android engineers would agree it’s so boring to type in @Composable, then type fun, function name and the parenthesis just to write a composable function.</p><p>Worry not, Android Studio provides a nice live template and it’s pretty easy to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*jCIDaH4Xthdu9HY5-ee8Bw.gif" /></figure><ol><li>Just type “comp” and press “tab”</li><li>Write your composable function name and press enter</li><li>Voila!</li></ol><p>But wait, that’s not all. Android Studio lets you create your custom live template. Here’s one example:</p><ol><li>Go to Android Studio Preferences(or Settings).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5f-ZPyxOFqond87uJGv26w.png" /></figure><p>2. Search “Live Templates” using the search bar as shown in the photo above</p><p>3. Click “Live Templates” in the side bar</p><p>4. Click + button on the top right</p><p>5. Copy and paste in below code into the input box at the bottom</p><pre>@androidx.compose.runtime.Composable<br>fun $NAME$(<br>    modifier: Modifier = Modifier<br>) {<br>$END$<br>}</pre><p>6. Click “Apply”</p><p>Now, by typing “compm” followed by “tab”, you can quickly jumpstart a composable function that has a modifier as a parameter.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef9db6615ea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose: Anchored Draggable Item in MotionLayout Part 2]]></title>
            <link>https://medium.com/@AungThiha3/jetpack-compose-anchored-draggable-item-in-motionlayout-part-2-c1fd94188e56?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1fd94188e56</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-animations]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 10:51:14 GMT</pubDate>
            <atom:updated>2023-09-16T10:51:14.225Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s the animation we’re developing in this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*uDRNG7Gl1lpDC69qTX551Q.gif" /></figure><p>In <a href="https://medium.com/@AungThiha3/jetpack-compose-anchored-draggable-item-in-motionlayout-part-1-8d5a1cde880f">Part 1</a>, we got the card draggable and animation working but the animation doesn’t encompass changing the size and color of the background of action buttons. We’ll address this in this article.</p><h3>Custom Attribute</h3><p>We want the color of the background of action buttons to turn red when the card is dragged up. In order to do that, we need to use a custom attribute.</p><p>Unlike MotionLayout in XML, custom attribute values are not set automatically by MotionLayout. We need to access the custom attribute value ourselves and apply it to our desired element in Compose.</p><p>Let’s start by adding the custom attribute in the MotionScene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4778ede17f06583bc7a5ba8111e32c8b/href">https://medium.com/media/4778ede17f06583bc7a5ba8111e32c8b/href</a></iframe><p>For more information about custom attributes of MotionLayout in Jetpack Compose, please refer to <a href="https://github.com/androidx/constraintlayout/wiki/Compose-MotionLayout-JSON-Syntax#custom-properties">syntax document by Google</a></p><p>It’s time to use the color value in RecipeDetail. There’re only two new lines of code for needed for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34a5247038ddb99bae3023f89a4e63e0/href">https://medium.com/media/34a5247038ddb99bae3023f89a4e63e0/href</a></iframe><p>It’s as simple as that for writing color transition</p><h3>Resize Background</h3><p>When we resize the background of action buttons, we just want 10dp margins around the buttons vertically but if we just set that in MotionScene, MotionLayout compress the buttons instead of making of the background bigger.</p><p>So, we need a workaround for this. Simplest solution I can think of is to add one Box above and another Box below the buttons. Let’s do that.</p><p>Please, add new constraints in the MotionScene for two new Boxes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be6265c3d4358b7e54a0e9080588e181/href">https://medium.com/media/be6265c3d4358b7e54a0e9080588e181/href</a></iframe><p>You can see the top constraints of the actions and text also need to be adjusted.</p><p>At this point, we have defined constraints for the two new Boxes in the MotionScene, but these two Boxes don’t exist in RecipeDetail yet. As the next step, let’s add them to our RecipeDetail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81efb395d868d88101cfc90dbe9fa8b1/href">https://medium.com/media/81efb395d868d88101cfc90dbe9fa8b1/href</a></iframe><p>It’s worth noting that the color value from the attribute of the actions is used for both of the new Boxes instead of creating a new one. If you want to be more explicit in the MotionScene, you can make actionTopBg and actionBottomBg have their own custom attributes, but it’s not necessary.</p><p>That’s all there is. Please, run the project and enjoy the result!</p><p>If you want the complete source code, it’s hosted on <a href="https://github.com/AungThiha/AnchoredDraggableItemMotionLayout/tree/main">Github</a>.</p><p>Hope you enjoyed the series!</p><h3>Useful Sources:</h3><p>These are the valuable sources I used to make my series happen.</p><ul><li><a href="https://blog.canopas.com/explore-compose-motionlayout-773a3462d787">Explore Compose MotionLayout</a></li><li><a href="https://www.valueof.io/blog/motionlayout-in-compose-motion-scene-json5">Using MotionLayout in Compose</a>, Basics of using MotionLayout in Compose</li><li><a href="https://github.com/androidx/constraintlayout/wiki/Compose-MotionLayout-JSON-Syntax">Compose MotionLayout JSON Syntax</a></li><li><a href="https://github.com/androidx/constraintlayout/tree/main/projects/ComposeConstraintLayout">Compose ConstraintLayout</a>, this includes samples for MotionLayout.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1fd94188e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose: Anchored Draggable Item in MotionLayout Part 1]]></title>
            <link>https://medium.com/@AungThiha3/jetpack-compose-anchored-draggable-item-in-motionlayout-part-1-8d5a1cde880f?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d5a1cde880f</guid>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 18:23:46 GMT</pubDate>
            <atom:updated>2023-09-18T07:54:04.735Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you need a draggable item that can have its contents animated? You have come to the right place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*uDRNG7Gl1lpDC69qTX551Q.gif" /></figure><p>This is what we’re going to build in this article. As you might have guessed from the title, we’re gonna use MotionLayout, which is a subclass of ConstraintLayout.</p><p>This article is inspired by <a href="https://blog.canopas.com/explore-compose-motionlayout-773a3462d787">an article</a> written by <a href="https://medium.com/@radhika.s_76503?source=post_page-----773a3462d787--------------------------------">Radhika S</a> but the onSwipe attribute in MotionScene file demonstrated in that article does not work. So, I decided to find a solution and write an article.</p><p>Enough of the backstory; let’s dive in.</p><h3>Create Project</h3><ul><li>Please, go ahead and create your project in Android Studio.</li><li>Make sure you choose “Compose Empty Activity”.</li></ul><h3>Create Layout</h3><p>To create the layout, first, add dependency for MotionLayout</p><pre>implementation &quot;androidx.constraintlayout:constraintlayout-compose:1.0.1&quot;</pre><p>Please, grab the cake photo from <a href="https://github.com/cp-radhika-s/ComposeMotionLayoutDemo/blob/master/app/src/main/res/drawable-v24/cake.jpeg">here</a> and add it into your drawable folder. (I’m referencing the cake photo from Github repo of where I got the UI idea from. If the photo is no longer available, please let me know.)</p><p>After that, add the layout file itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f78f0405a7f76aba5406e834ced68e6/href">https://medium.com/media/2f78f0405a7f76aba5406e834ced68e6/href</a></iframe><p>When you import missing classes, make sure you choose them from compose packages. There’s usually similar classes with the same names in other packages. So, please, make sure you choose the ones from compose package.</p><p>Don’t worry about the empty string in remember and the 0f progress passed into MotionLayout for now. We’ll work on them later.</p><p>layoutId is used to help MotionLayout identify the items, just like we do with ConstraintLayout.</p><p>Alright, let’s use that RecipeDetail compose in the root of your compose. In my case, this is what it looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88bbfed4b86a99c5883003e688fcf476/href">https://medium.com/media/88bbfed4b86a99c5883003e688fcf476/href</a></iframe><p>Let’s run the project. Wait!!! What’s going on?!!! Blank white screen!!!</p><p>Worry not! It’s happening because we haven’t placed any constraints yet.</p><h3>MotionScene</h3><p>To define constraints, we need to create what they call MotionScene.</p><p>There are two ways to do it:</p><ol><li>MotionCompose</li><li>Json</li></ol><p>We’ll use json in this article.</p><p>In MotionScene, we need to define start point and end point. MotionLayout will figure out how to animate between these two points. These points are known as ConstraintSet. You can have more than two ConstraintSets when you need to but that’s a story for another day.</p><p>Let’s start with the start point. This file should be inside res/raw and the file extension should be json5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734d3b26af0090d9afb7d10856d30d0a/href">https://medium.com/media/734d3b26af0090d9afb7d10856d30d0a/href</a></iframe><p>in top: [&#39;parent&#39;, &#39;top&#39;, 200], 200 is a density pixel(dp). It’s the margin to the top of parent.</p><p>the value of height is also dp.</p><p>(I hope the rest of this file is self-explanatory. If it’s not clear, I would really appreciate it if you let me know. That will help me improve my blogging skills)</p><p>For the end point, just put in the same content as start point for now. We just wanna display the initial UI at this stage.</p><p>Next, let’s use the MotionScene json5 file in MotionLayout. Remember the empty string at the top of the RecipeDetail compose function. That’s where we use this json5 file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/933fb62c03b615f31393a48842ec7cea/href">https://medium.com/media/933fb62c03b615f31393a48842ec7cea/href</a></iframe><p>Let’s run the project. The UI isn’t exciting at this point and you can’t drag anything yet. There’s not even a card UI. We’ll add a card in the next stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*atUlhcKzwzsCHC8xpRqsJA.png" /></figure><h3>Card</h3><p>Normally the title, the action buttons and the body message would be inside Card compose but because MotionLayout can’t animate nested items. We need to make the layout flat.</p><p>Let’s add the card UI with Box below the cake Image and above the title Text. The reason it needs to be after Image is because we want the card to be on top of the Cake. Similarly, we want the card to be underneath the texts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/254913fcd33b7d031ba93bb014ca9acd/href">https://medium.com/media/254913fcd33b7d031ba93bb014ca9acd/href</a></iframe><p>Just like our first step, the card won’t show up because we don’t have constraints for it yet.</p><p>Let’s add constraint for the card in the MotionScene file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e01214c9d61bc313228a439866ef752/href">https://medium.com/media/6e01214c9d61bc313228a439866ef752/href</a></iframe><p>You should now see the card but you can’t drag it yet</p><h3>Make The Card Draggable</h3><p>First, we need to define end point in the MotionScene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2290dc7eb82192b2875bf3287ef36bcd/href">https://medium.com/media/2290dc7eb82192b2875bf3287ef36bcd/href</a></iframe><p>Unlike top, height, end, etc., the value of translationY is not density pixel. It’s pixel.</p><p>You won’t be able to drag yet but to make sure the constraints of end point is correct, please, switch the contents of start and end temporarily and run the project to see if the constraints for end point is correct.</p><p>Notice that the date is hidden. We set the visibility of date to be gone . MotionLayout is smart enough find out how to transition into hidden state smoothly.</p><p>The background of the action buttons doesn’t turn red and its height is not the same as in the video. We’ll fix that later.</p><p>After you’ve checked the constraints for end point are correct, please, switch the contents of start and end back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*IRzXGz1wX3uN4yYFi3kgyQ.jpeg" /></figure><p>To make the card draggable, next step is to use AnchoredDraggable from compose foundation library.</p><p>Please, be aware that this is an experimental API but since Swipeable is deprecated, AnchoredDraggable is the only thing we can use with MotionLayout for this kind of animation unless you implement everything from scratch. (If you do find a different solution that doesn’t involve an experimental API and it’s not writing the whole thing from scratch, please, do let me know in the comment section.)</p><p><a href="https://developer.android.com/jetpack/compose/touch-input/pointer-input/migrate-swipeable">https://developer.android.com/jetpack/compose/touch-input/pointer-input/migrate-swipeable</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77CWqvr0-1_iR_vWrdijZw.png" /></figure><p>Anyway, I’ll use AnchoredDraggable for this article. Please, import compose foundation library. At the time of writing this article, stable version does not have AnchoredDraggable yet. So, I’m using alpha.</p><pre>implementation &#39;androidx.compose.foundation:foundation:1.6.0-alpha05&#39;</pre><p>Please, copy-paste AnchoredDraggableCardState.kt into your project. We’ll use these enum values as keys when we tell AnchoredDraggable API what the anchored points are.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/632a99a50a7da3de36af14c41dbb43b5/href">https://medium.com/media/632a99a50a7da3de36af14c41dbb43b5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f64ee34473697a327db8b831f43387b/href">https://medium.com/media/0f64ee34473697a327db8b831f43387b/href</a></iframe><p>Because we want the gap between the top and the card to be 200dp when the card is dragged down, we set draggedDownAnchorTop to AnchoredDraggableCardState.DRAGGED_DOWN inside DraggableAnchors.</p><p>When the card is dragged up, it’s obvious there will be no gap between the top and the card. So, AnchoredDraggableCardState.DRAGGED_UP has 0f.</p><p>Please, be aware that these anchor points are not actually used to move the card. Rather, they are used to move the gesture listener area. The card itself is moved by the MotionLayout but we need to move the gesture listener area too because we want the card to move only when the user drags by the card, not when they drag by other areas.</p><p>Back to AnchoredDraggable, we need tell the AnchoredDraggable which point we want to start first. You can see we’re passing AnchoredDraggableCardState.Dragged_DOWN into AnchoredDraggableState.</p><p>For other arguments of AnchoredDraggableState, please, look into <a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/gestures/AnchoredDraggableState">official document</a> to understand more.</p><p>Notice that MotionLayout also now has proper progress set instead of 0f</p><p>Final step in making the card draggable is to set the AnchoredDraggableState onto the card.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff144ada355c58b07ffd008a20b96921/href">https://medium.com/media/ff144ada355c58b07ffd008a20b96921/href</a></iframe><p>Let’s run the project.</p><p>You’re probably get errors saying you need to update your compileSdk to 34. If you get it, please, update the compileSdk and targetSdk to 34 or higher if there’s higher version already released.</p><p>After updating the compileSdk and targetSdk, please, re-run the project.</p><p>If you can’t drag the card and if you’re seeing the card at the top, you probably forgot to switch the start and end back. Please, remember we temporarily switched them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*8H13IC5nlJMQ9MGA7EgD_Q.gif" /></figure><p>Whoo hoo!!! We can now drag the card!!!</p><p>I hope you enjoyed the article! Please, give it some claps and please, give me some feedbacks. So, I can improve my blogging skills to help fellow developers more and more.</p><p>In <a href="https://medium.com/@AungThiha3/jetpack-compose-anchored-draggable-item-in-motionlayout-part-2-c1fd94188e56">part 2</a>, I explain how to increase the size of the background of action buttons and how to use a custom attribute from MotionScene to animate the color transition.</p><p>See you in <a href="https://medium.com/@AungThiha3/jetpack-compose-anchored-draggable-item-in-motionlayout-part-2-c1fd94188e56">part 2</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d5a1cde880f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking JSON responses from Retrofit calls and make them RxJava/RxKotlin Observable for unit…]]></title>
            <link>https://medium.com/@AungThiha3/mocking-json-responses-from-retrofit-calls-and-make-them-rxjava-rxkotlin-observable-for-unit-6fce27440e3d?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fce27440e3d</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 14:03:59 GMT</pubDate>
            <atom:updated>2019-08-03T14:03:59.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mocking JSON responses from Retrofit calls and make them RxJava/RxKotlin Observable for unit testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*PiuW_tOdEBjB9GpLLU96og.jpeg" /><figcaption>Beauty of my hometown, Mandalay</figcaption></figure><p>Previously, I wrote about Handling different status codes from Retrofit calls differently with RxJava. This post is kind of part 3 but you don’t really need to read part 1 or 2 first to understand this but if you’re interested, please do check my previous posts.</p><p>This is one of the posts from the series I’m writing.</p><ol><li><a href="https://medium.com/@AungThiha3/chaining-and-running-retrofit-calls-in-parallel-with-rxjava-2c6bf5f6d598">Chaining and Running Retrofit calls in parallel with RxJava</a></li><li><a href="https://medium.com/@AungThiha3/handling-different-status-codes-from-retrofit-calls-differently-with-rxjava-4d2ae1000a17">Handling different status codes from Retrofit calls differently with RxJava</a></li><li>Mocking JSON responses from Retrofit calls and make them Observable for unit testing (You’re here)</li></ol><p>Add mock dependency in your gradle</p><pre>dependencies {<br>    testImplementation &quot;org.mockito:mockito-inline:{latest_version_here}&quot;<br>}</pre><p>One thing to note is in my previous posts, I used <strong>Observable</strong>. In this example, I’m using <strong>Single</strong>. If you haven’t checked the difference, you can google the difference between <strong>Observable, Single, Maybe, Completable</strong> and <strong>Flowable</strong>.</p><p>Now, Let’s look how we test a mock retrofit</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcf670072ada1a13c3d8446847150b24/href">https://medium.com/media/fcf670072ada1a13c3d8446847150b24/href</a></iframe><p>I hope the comments and the code is clear enough. If you need any explanation, please let me know. I’ll be happy to add.</p><p>Thank you for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fce27440e3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling different status codes from Retrofit calls differently with RxJava]]></title>
            <link>https://medium.com/@AungThiha3/handling-different-status-codes-from-retrofit-calls-differently-with-rxjava-4d2ae1000a17?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d2ae1000a17</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[retrofit]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Sun, 25 Nov 2018 03:40:19 GMT</pubDate>
            <atom:updated>2019-08-03T14:04:52.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nC2WmtK_oCTiaFpi6wrLg.jpeg" /><figcaption>Beauty of my hometown, Mandalay</figcaption></figure><p>Previously, I wrote about Chaining and Running Retrofit calls in parallel with RxJava. This post is kind of part 2 but you don’t really need to read that first to understand this but if you’re interested, please do check my previous post.</p><p>This is one of the posts from the series I’m writing.</p><ol><li><a href="https://medium.com/@AungThiha3/chaining-and-running-retrofit-calls-in-parallel-with-rxjava-2c6bf5f6d598">Chaining and Running Retrofit calls in parallel with RxJava</a></li><li>Handling different status codes from Retrofit calls differently with RxJava (You’re here)</li><li><a href="https://medium.com/@AungThiha3/mocking-json-responses-from-retrofit-calls-and-make-them-rxjava-rxkotlin-observable-for-unit-6fce27440e3d">Mocking JSON responses from Retrofit calls and make them Observable for unit testing</a></li></ol><p>Previous, our PromotionService looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2666c8dcf76cd2f8c3e7791b27fe021/href">https://medium.com/media/b2666c8dcf76cd2f8c3e7791b27fe021/href</a></iframe><p>The problem with that approach is that we can’t get status code. Not only that, we can’t call any useful methods that come with the retrofit’s <em>Response </em>class<em>. </em>So, we need to wrap our response with <em>Response</em> class like so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1edbae6337261e588a0b512fd31725aa/href">https://medium.com/media/1edbae6337261e588a0b512fd31725aa/href</a></iframe><p>Now, we can check status codes in Repository class. Just for the purpose of demonstrating an example usage, we’re gonna check if the status code is 204 and return an empty <em>Optional</em> if it is. We need the <em>Optional</em> class because 204 has nothing to emit and RxJava doesn’t let us emit null. Plus, we don’t want our presenter to recognize empty responses as errors because we may want to show the users something like “no content available” and clearly having no content is not an error.</p><p>Don’t get frustrated over the fact that Android API lower than 24 doesn’t support Java 8 Optional. I have written a similar class based on it and it’s provided below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd46e512dca76a53c0858fd9d88a3998/href">https://medium.com/media/cd46e512dca76a53c0858fd9d88a3998/href</a></iframe><p>Now, we can handle different status codes differently in our Repository class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc5518be06e98cc9976d262978e7c56f/href">https://medium.com/media/bc5518be06e98cc9976d262978e7c56f/href</a></iframe><p>Finally, in our presenter, we can receive empty response as <em>Optional </em>object<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c4b7cb6026b7862806920a3bd192aa1/href">https://medium.com/media/2c4b7cb6026b7862806920a3bd192aa1/href</a></iframe><p>There we have it. Empty contents from Retrofit call is now nicely handled. As a bonus, I use <em>onErrorResumeNext </em>to continue showing sales even if fetching ads fails.</p><p>I hope the comments in the code explains well enough. Let me know if it’s still confusing, I’ll try my best to explain better.</p><p>If you like my post, please give it some claps.</p><p>Happy coding!</p><p><a href="https://medium.com/@AungThiha3/mocking-json-responses-from-retrofit-calls-and-make-them-rxjava-rxkotlin-observable-for-unit-6fce27440e3d">Mocking JSON responses from Retrofit calls and make them RxJava/RxKotlin Observable for unit…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d2ae1000a17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaining and Running Retrofit calls in parallel with RxJava]]></title>
            <link>https://medium.com/@AungThiha3/chaining-and-running-retrofit-calls-in-parallel-with-rxjava-2c6bf5f6d598?source=rss-a9a6422dc570------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c6bf5f6d598</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Aung Thiha]]></dc:creator>
            <pubDate>Sat, 17 Nov 2018 08:14:33 GMT</pubDate>
            <atom:updated>2019-08-03T14:06:15.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aaEebyW-Rlki0OlNreaQg.jpeg" /><figcaption>Beauty of my hometown, Mandalay</figcaption></figure><p>I’ve been playing around with RxJava for the past few days and I find it really enjoyable and really useful.</p><p>In my quest to fight my FOMO, I tried chaining a retrofit call with another two calls that are zipped together and run in parallel in two different threads and finally load the results into UI only when all of them are done. It’s like a magic. It feels amazing. Then, I immediately had an urge to share this amazing thing that I just learned. So, here I am writing a post.</p><p>I will write what I’ve learned in a series.</p><ol><li>Chaining and Running Retrofit calls in parallel with RxJava (You’re here)</li><li><a href="https://medium.com/@AungThiha3/handling-different-status-codes-from-retrofit-calls-differently-with-rxjava-4d2ae1000a17">Handling different status codes from Retrofit calls differently with RxJava</a></li><li><a href="https://medium.com/@AungThiha3/mocking-json-responses-from-retrofit-calls-and-make-them-rxjava-rxkotlin-observable-for-unit-6fce27440e3d">Mocking JSON responses from Retrofit calls and make them Observable for unit testing</a></li></ol><p>Before I dive into it, let me friendly inform you that this is my first post and this is merely what I’ve learned in the past few days as a brand new user of RxJava rather than an experienced one. So, if you find some mistakes or know better approach, please kindly point me out and it would be appreciated.</p><p>Furthermore, please be advised that this post assumes you’re already familiar with Dagger 2 and MVP design pattern.</p><p>Now, let’s dive into it. Imagine you have three api calls that go something like this in sequence</p><ol><li>Find current promotion from a promotion list</li><li>Get a list of items that are promoted in current promotion</li><li>Get a list of ads in current promotion</li></ol><p>You can see that 2 and 3 don’t need to be run sequentially. They can be run in parallel when 1 is done so that the results can be loaded into UI faster. RxJava makes it easy to achieve this.</p><p>Let’s write our Retrofit interface first</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c745de2192c78896f46091bf880b30/href">https://medium.com/media/b3c745de2192c78896f46091bf880b30/href</a></iframe><p>Now, it’s turn for our Repository class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17245954d37cc0dc4fe62c0a03066bb3/href">https://medium.com/media/17245954d37cc0dc4fe62c0a03066bb3/href</a></iframe><p>Although we’re not doing anything useful in the Repository class at this stage, we will in my next post. For now, PromotionRepository is added just to check on which thread the api calls will run. We also need a little help from map operator to do it. (If you know a better way to check threads, please point me out 🙂)</p><p>Finally, we can write our Presenter class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0940076d8554bd043323f9efd3ab709/href">https://medium.com/media/d0940076d8554bd043323f9efd3ab709/href</a></iframe><p>Now, let’s run our app to see if we’re successfully running Retrofit calls as we desire.</p><pre>D/RxJavaThread: fetchPromotions: RxCachedThreadScheduler-1<br>D/RxJavaThread: fetchSales: RxCachedThreadScheduler-1<br>D/RxJavaThread: fetchAds: RxNewThreadScheduler-1</pre><p>Woo Hoo! “fetchSales” and “fetchAds” happen only after “fetchPromotions” and they run in two different threads in parallel.</p><p>I hope my post is helpful to others. If you enjoy my post, please give it some claps.</p><p>More posts coming soon….. ✍️</p><p><a href="https://medium.com/@AungThiha3/handling-different-status-codes-from-retrofit-calls-differently-with-rxjava-4d2ae1000a17">Handling different status codes from Retrofit calls differently with RxJava</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c6bf5f6d598" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>