<?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 Masoud Fallahpour on Medium]]></title>
        <description><![CDATA[Stories by Masoud Fallahpour on Medium]]></description>
        <link>https://medium.com/@mfallahpour?source=rss-78bfa2974575------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YQlUIOEt8A7jiuEzEr7aZA.jpeg</url>
            <title>Stories by Masoud Fallahpour on Medium</title>
            <link>https://medium.com/@mfallahpour?source=rss-78bfa2974575------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:46:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mfallahpour/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[Breaking Out of My “Android Development” Comfort Zone]]></title>
            <link>https://mfallahpour.medium.com/breaking-out-of-my-android-development-comfort-zone-a766ea5006e9?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/a766ea5006e9</guid>
            <category><![CDATA[soft-skills]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 13:08:39 GMT</pubDate>
            <atom:updated>2024-03-31T13:08:39.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8oZ_wzZ8BNOyt1RC" /><figcaption>Photo by <a href="https://unsplash.com/@jasonhogan?utm_source=medium&amp;utm_medium=referral">Jason Hogan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I’ll discuss venturing beyond my “Android development” comfort zone. I’ll start by giving my professional background, follow-up with the reasons behind my decision to embrace this challenge, then share the process I undertook to achieve this, and conclude by reflecting on my experience so far.</p><h3>My professional background</h3><p>I’ve been doing software engineering for the past 8 years. My professional journey began in Java development. After exploring the domain for nearly a year, I shifted my focus towards Android development where I spent the subsequent 7 years working mostly on video streaming apps. I’ve worked at several companies and for the past 9 months I’ve been working at <a href="https://www.linkedin.com/company/klarna/">Klarna</a>.</p><h3>Why breaking out of my comfort zone?</h3><p>Based on my professional background, I always identified myself as an “Android Software Engineer.” That was until a year ago, when I decided to be a “Software Engineer.”</p><p>I was quite comfortable with Android development and I was enjoying it, so much that I turned down some opportunities in backend, iOS, and web development. But eventually, I felt as though I’d hit the ceiling. This isn’t to say I’d mastered every facet of Android development. Rather, I felt it was time to explore other platforms. My decision was mainly driven by the following reasons:</p><ul><li><strong>Curiosity</strong>: I was always curious about other platforms and had tried web and backend development but never beyond toy projects. I had never spent time to get comfortable with them. This time I was more curious than ever to try them.</li><li><strong>New learning opportunities</strong>: As software engineers, we possess a distinct knack for perpetual learning, whether it be a new programming language, a framework, or a tool. Despite continuously learning about Android, I decided to widen my scope. This time I wanted to learn other platforms which meant a ton of new learning was ahead of me and what could be better than that!</li><li><strong>Professional growth</strong>: I admired many senior software engineers and noticed that they shared some common traits. A common characteristic was their T-shaped knowledge profile. While they specialized in one platform — say, Android — they also had a working understanding of other platforms. To further my professional growth, it seemed necessary that I adopt the way of the T-shaped software engineer. Such an engineer’s forte lies in their holistic viewpoint when devising a feature, solution, and so forth. Given this comprehensive perspective, they can assess the situation from multiple angles, providing valuable insights to the existing discourse.</li></ul><h3>How I broke out of my comfort zone</h3><p>A year ago when I decided to try other platforms I had two options on the table:</p><ol><li>To stay in my previous company but change my team so I could start working on something other than Android.</li><li>Finding a new job where I could try something different.</li></ol><p>The first option didn’t work. I tried to change my team but after sometime I came to the conclusion that it was not going to be easy because of how my previous company was setup. It was more complicated than I expected!</p><p>By the time I was convinced I could not achieve what I had in my mind in my previous company, I started looking for a job and after some time joined the mobile SDK team at Klarna.</p><p>Joining the mobile SDK team at Klarna fundamentally changed two aspects of my professional career. Firstly, I switched from video streaming into the banking and payments industry. Secondly, I was presented with an opportunity to work on iOS, React Native, Flutter, and even some web development, in addition to Android. This was precisely what I was looking for: the chance to venture into new territories!</p><p>During my initial months of onboarding, my focus was primarily Android-based, but gradually I also began working on other platforms including iOS, React Native, and web. Now, when I look at the backlog of the tasks I’ve done I see a healthy amount of Android, iOS, React Native, and web tasks and this means I’ve managed to get out of my “Android development” comfort zone!</p><h3>Reflecting on my journey so far</h3><p>When I look back at my decision to break out of my “Android development” comfort zone, I think it was hell of a good decision! Now when someone talks about iOS, React Native, web, etc I have a rough idea of what they’re talking about and how things work on those platforms.</p><p>To wrap up, here are some key insights I learned along the way:</p><ol><li><strong>Start before you’re ready! </strong>You do not need to grasp a platform in its entirety before embarking on working with it. A week or two spent acquainting yourself with the basics is sufficient. As you progress, you’ll naturally acquire a deeper understanding, uncover best practices, and learn tips and tricks.</li><li><strong>Embrace challenges.</strong> Starting on a new platform can seem daunting initially, but rest assured you’ll get the hang of it swiftly. With the right motivation, you’ll soon find yourself proficient and productive.</li><li><strong>Do not be afraid to try new things</strong>. Do not shy away from trying new things. For me, it was this fear that had previously prevented me from exploring new things. Overcoming this fear is the very first step towards stepping out of your comfort zone.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a766ea5006e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Android Intent Redirection Vulnerability and How to Prevent It]]></title>
            <link>https://mfallahpour.medium.com/what-is-android-intent-redirection-vulnerability-and-how-to-prevent-it-7cea70b052db?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cea70b052db</guid>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 11:59:08 GMT</pubDate>
            <atom:updated>2023-11-17T14:13:03.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mbe6ZiCsvxbw2d55" /><figcaption>Photo by <a href="https://unsplash.com/@srhhrbch?utm_source=medium&amp;utm_medium=referral">Siarhei Horbach</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to the security of an Android app there are lots of <a href="https://developer.android.com/privacy-and-security/risks/">security risks</a> that one should be aware of. One such risk is the <a href="https://medium.com/r?url=https%3A%2F%2Fdeveloper.android.com%2Fprivacy-and-security%2Frisks%2Fintent-redirection%23%3A%7E%3Atext%3DPLATFORM%253A%2520Platform%2520Interaction-%2COverview%2Ccontext%2520of%2520a%2520vulnerable%2520app.">Intent Redirection</a> vulnerability.</p><p>In this post I’ll write about what Intent Redirection vulnerability is and how to prevent it. Let’s get started.</p><h3>What is Intent Redirection Vulnerability?</h3><p>An intent redirection occurs when an attacker can partly or fully control the contents of an intent used to launch a new component in the context of a vulnerable app.</p><p>Using this vulnerability, an attacker for example can access the components of an app that are only accessible to the app itself by default. If these components are sensitive and should not be accessed by third-party apps then things may go sour!</p><h3>How Intent Redirection Vulnerability Happens?</h3><p>To see how this vulnerability happens we’re going to consider two apps:</p><ul><li>a vulnerable app which is susceptible to the Intent Redirection vulnerability,</li><li>an attacker app which we use to exploit the vulnerable app.</li></ul><h4>Vulnerable App</h4><p>Imagine the vulnerable app has three Activities:</p><ul><li>MainActivity: this is the main Activity of the app and does nothing special.</li><li>LauncherActivity: this is the Activity that we use to launch other Activities in our app, hence the name! This is the vulnerable Activity. We will look at its source code shortly.</li><li>SecretActivity: this is the Activity which is private to our app and cannot be launched by any third-party app.</li></ul><p>Here is the manifest of the app:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;application<br>        android:allowBackup=&quot;true&quot;<br>        android:dataExtractionRules=&quot;@xml/data_extraction_rules&quot;<br>        android:fullBackupContent=&quot;@xml/backup_rules&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;<br>        android:label=&quot;@string/app_name&quot;<br>        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;<br>        android:supportsRtl=&quot;true&quot;<br>        android:theme=&quot;@style/Theme.IntentRedirectionVulnerability&quot;<br>        tools:targetApi=&quot;31&quot;&gt;<br>        &lt;activity<br>            android:name=&quot;.MainActivity&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br><br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>        &lt;activity<br>            android:name=&quot;.LauncherActivity&quot;<br>            android:exported=&quot;true&quot; /&gt;<br>        &lt;activity<br>            android:name=&quot;.SecretActivity&quot;<br>            android:exported=&quot;false&quot; /&gt;<br>    &lt;/application&gt;<br><br>&lt;/manifest&gt;</pre><p>As can be seen SecretActivity’s android:exported is set to false which means only the app itself has access to it. In other words, no third-party app can access it.</p><p>Now let’s take a look at the source code of LauncherActivity:</p><pre>import android.content.Intent<br>import android.os.Bundle<br>import androidx.appcompat.app.AppCompatActivity<br><br>class LauncherActivity : AppCompatActivity() {<br>    companion object {<br>        const val KEY_INTENT = &quot;key_intent&quot;<br>    }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_launcher)<br>        val intent = intent.getParcelableExtra&lt;Intent&gt;(KEY_INTENT)<br>        intent?.let {<br>            startActivity(intent)<br>        }<br>    }<br>}</pre><p>As can be seenLauncherActivity receives an Intent as a Parcelable and calls startActivity using the received Intent.</p><p>The above code is short and may seem innocent but that’s enough code for introducing the Intent Redirection vulnerability into your app.</p><p>The problem here is that the Intent we’re receiving may come from an untrusted source (from an attacker for example!) and without doing any sanitization, we’re executing it.</p><p>In simple terms, calling startActivity, startService, bindService, or sendBroadcast with an Intent that you have received and you do not know its origin is a security risk.</p><h4>Attacker App</h4><p>Now let see how we can exploit this vulnerability using a very simple app!</p><p>This app has a single Activity called MainActivity. It has a single button that upon clicking, sends an Intent to the vulnerable app.</p><pre>import android.content.ComponentName<br>import android.content.Intent<br>import android.os.Bundle<br>import android.widget.Button<br>import androidx.appcompat.app.AppCompatActivity<br><br>class MainActivity : AppCompatActivity() {<br>    companion object {<br>        const val VULNERABLE_APP_PACKAGE_NAME = &quot;ir.fallahpoor.intentredirectionvulnerability&quot;<br>    }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        findViewById&lt;Button&gt;(R.id.sendIntentButton).setOnClickListener {<br>            startActivity(createIntent())<br>        }<br>    }<br><br>    private fun createIntent(): Intent {<br>        val intentExtra = Intent().apply {<br>            val vulnerebleAppInaccessibleClassName = &quot;$VULNERABLE_APP_PACKAGE_NAME.SecretActivity&quot;<br>            setComponent(<br>                ComponentName(<br>                    VULNERABLE_APP_PACKAGE_NAME,<br>                    vulnerableAppInaccessibleClassName<br>                )<br>            )<br>        }<br>        val vulnerableAppClassName = &quot;$VULNERABLE_APP_PACKAGE_NAME.LauncherActivity&quot;<br>        val intent = Intent().apply {<br>            setComponent(ComponentName(VULNERABLE_APP_PACKAGE_NAME, vulnerableAppClassName))<br>            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)<br>            putExtra(&quot;key_intent&quot;, intentExtra)<br>        }<br>        return intent<br>    }<br>}</pre><p>The Intent we create will start the MainActivity of the vulnerable app. This Intent has another Intent as part of its data. We use this nested Intent to start the SecretActivity.</p><p>Now if we run the attacker app on the same device that the vulnerable app is installed and click the “Send Intent” button SecretActivity will be launched. So SecretActivity is exposed to third-party apps!</p><p>Remember that SecretActivity was not supposed to be accessible by any third-party app but using the Intent Redirection vulnerability we managed to access it!</p><h3>How to Prevent Intent Redirection Vulnerability?</h3><p><a href="https://support.google.com/faqs/answer/9267555">This</a> official guide from Google mentions a couple of ways that can be used to prevent this vulnerability. I’ll just mention the options briefly. For more in-depth explanation please refer to the linked guide.</p><ul><li><strong>Option 1: </strong>If possible make the component which is doing the Intent redirection private. In case of the vulnerable app that we developed it means updating the value of android:exported to false for LauncherActivity.</li><li><strong>Options 2:</strong> Making sure that the received Intent is coming from a trustworthy source.</li><li><strong>Options 3:</strong> Making sure that the to-be-launched Intent is not harmful.</li></ul><p>There’s also a completely different solution which suggests using a PendingIntent instead of an Intent. To read about this solution please refer to <a href="https://medium.com/androiddevelopers/android-nesting-intents-e472fafc1933">here</a>.</p><p>And that was all you need to know about Intent Redirection vulnerability and how to prevent it.</p><p><a href="https://github.com/MasoudFallahpour/IntentRedirectionVulnerableApp">Here</a> you can access the source code of the vulnerable app and <a href="https://github.com/MasoudFallahpour/IntentRedirectionAttackerApp">here</a> is the source code of the attacker app.</p><h3>References</h3><ul><li><a href="https://developer.android.com/quality/privacy-and-security">Design for Safety | App quality | Android Developers</a></li><li><a href="https://developer.android.com/privacy-and-security/risks/intent-redirection">Intent redirection | App quality | Android Developers</a></li><li><a href="https://medium.com/androiddevelopers/android-nesting-intents-e472fafc1933">Android Nesting Intents</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cea70b052db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Representing multiple values in Kotlin: List vs. Sequence vs. Flow]]></title>
            <link>https://mfallahpour.medium.com/representing-multiple-values-in-kotlin-list-vs-sequence-vs-flow-f51d6c98c590?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/f51d6c98c590</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[sequence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 20:48:30 GMT</pubDate>
            <atom:updated>2023-03-07T20:48:30.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maopCXYWOVmJTFaq567oTQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@solenfeyissa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Solen Feyissa</a> on <a href="https://unsplash.com/photos/IfWFKG3FXE4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When dealing with multiple values in Kotlin, there are several options available. In this post will look at List, Sequence, and Flow. In order to have a better understanding of these 3 options and how they differ we will define a hypothetical problem and try to refine our solution until we reach the desired outcome.</p><h3>The problem</h3><p>We want to write a function that returns the first 10 <a href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci</a> numbers. We assume that computing each number takes 500 milliseconds. Also, let’s assume that the ideal solution we are looking for should have the following properties:</p><ol><li>The solution should be non-blocking meaning that at no point it should ever block the main thread,</li><li>Each number should be available as soon as it’s computed.</li></ol><h3>List</h3><p>We will start with defining the following function which returns the first 10 Fibonacci numbers as a List.</p><pre>fun fibonacciList(): List&lt;Int&gt; {<br>    var first = 0<br>    var second = 1<br>    val numbersList = mutableListOf&lt;Int&gt;().apply {<br>        Thread.sleep(500)<br>        add(first)<br>        Thread.sleep(500)<br>        add(second)<br>    }<br>    repeat(8) {<br>        Thread.sleep(500)<br>        val t = second<br>        second += first<br>        first = t<br>        numbersList += second<br>    }<br>    return numbersList<br>}</pre><p>In the above code, we used Thread.sleep to simulate the time it takes to compute a number.</p><p>Let’s call the above function in the following way and see what’s printed:</p><pre>fun main() {<br>    lateinit var numbers: List&lt;Int&gt;<br>    val duration = measureTimeMillis {<br>        numbers = fibonacciList()<br>    }<br>    println(&quot;fibonacciList returned after $duration millis.&quot;)<br>    numbers.forEach { print(&quot;$it &quot;) }<br>}</pre><p>The above code outputs something like the following:</p><pre>fibonacciList returned after 5034 millis.<br>0 1 1 2 3 5 8 13 21 34</pre><p>We can observe two things based on the above output:</p><ol><li>Calling fibonacciList blocks the main thread until it returns,</li><li>When calling fibonacciList, we have no numbers for roughly 5 seconds and after that, we’ll have all the numbers at once.</li></ol><p>So using a List as the return type of the function was not a good idea as it did not satisfy the properties of the solution we were looking for. Next, let’s try <a href="https://kotlinlang.org/docs/sequences.html">Sequence</a>.</p><h3>Sequence</h3><p>This time we’ll use a Sequence as the return type of the function, resulting in the following code:</p><pre>fun fibonacciSequence(): Sequence&lt;Int&gt; {<br>    var first = 0<br>    var second = 1<br>    val numbersSequence = sequence {<br>        Thread.sleep(500)<br>        yield(first)<br>        Thread.sleep(500)<br>        yield(second)<br>        repeat(8) {<br>            Thread.sleep(500)<br>            val t = second<br>            second += first<br>            first = t<br>            yield(second)<br>        }<br>    }<br>    return numbersSequence<br>}</pre><p>We call the above function like this:</p><pre>fun main() {<br>    lateinit var numbers: Sequence&lt;Int&gt;<br>    val duration1 = measureTimeMillis {<br>        numbers = fibonacciSequence()<br>    }<br>    println(&quot;fibonacciSequence returned after $duration1 millis.&quot;)<br>    val duration2 = measureTimeMillis {<br>        numbers.forEach { print(&quot;$it &quot;) }<br>    }<br>    println(&quot;\nIt took $duration2 millis to print all numbers.&quot;)<br>}</pre><p>Running the above code generates an output like this:</p><pre>fibonacciSequence returned after 8 millis.<br>0 1 1 2 3 5 8 13 21 34 <br>It took 5040 millis to print all numbers.</pre><p>When we run the above code we can see that fibonacciSequence is non-blocking and it returns quickly. But calling forEach on the Sequence is blocking, and it takes roughly 5 seconds for all numbers to be printed. The good news is that each number is printed as soon as it’s available. So we made some progress! Let’s move on to our next option which is <a href="https://kotlinlang.org/docs/flow.html">Flow</a>.</p><h3>Flow</h3><p>Let’s write the same function but this time using Flow as its return type:</p><pre>fun fibonacciFlow(): Flow&lt;Int&gt; {<br>    var first = 0<br>    var second = 1<br>    val numbersFlow = flow {<br>        delay(500)<br>        emit(first)<br>        delay(500)<br>        emit(second)<br>        repeat(8) {<br>            delay(500)<br>            val t = second<br>            second += first<br>            first = t<br>            emit(second)<br>        }<br>    }<br>    return numbersFlow<br>}</pre><p>Let’s call the above function in the following way:</p><pre>fun main() = runBlocking {<br>    lateinit var numbers: Flow&lt;Int&gt;<br>    val duration = measureTimeMillis {<br>        numbers = fibonacciFlow()<br>    }<br>    println(&quot;fibonacciFlow returned after $duration millis.&quot;)<br>    launch {<br>        numbers.collect { print(&quot;$it &quot;) }<br>    }<br>    println(&quot;Main thread is not blocked!&quot;)<br>}</pre><p>Running the code above produces an output like this:</p><pre>fibonacciFlow returned after 6 millis.<br>Main thread is not blocked!<br>0 1 1 2 3 5 8 13 21 34</pre><p>By running the above code we can observe the following things:</p><ol><li>The whole code is non-blocking,</li><li>Each number is printed as soon as it’s produced.</li></ol><p>This means we’ve found our ideal solution! We have a function that generates the first 10 Fibonacci numbers. It’s not blocking the main thread and each number is available as soon as it’s produced.</p><p><em>And that’s a wrap!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f51d6c98c590" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Any, Nothing, and Unit in Kotlin]]></title>
            <link>https://mfallahpour.medium.com/any-nothing-and-unit-in-kotlin-6b0b9779c197?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0b9779c197</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 21:11:34 GMT</pubDate>
            <atom:updated>2024-07-26T07:41:56.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkwaIuD0u-oYXm3dEKm4tg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@cmzw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mingwei Lim</a> on <a href="https://unsplash.com/photos/FWp9yrgW658?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this short post, we’ll take a look at some of the special types in Kotlin. These types are Any, Nothing, and Unit. You may have used some or all of them but may not know the exact difference between them. If that’s the case then read on!</p><h3>Any</h3><p>The official documentation of Any states:</p><blockquote>The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.</blockquote><p>This means Any is the parent class of any class you define in Kotlin. This means if you follow the chain of parents of a class you will finally end up at Any. It’s the exact equivalent of Object in Java.</p><p>Here is the definition of Any. Based on the above paragraph and the following definition, every class in Kotlin has methods equals, hashCode and toString.</p><pre>public open class Any {<br>    public open operator fun equals(other: Any?): Boolean<br><br>    public open fun hashCode(): Int<br><br>    public open fun toString(): String<br>}</pre><h3>Nothing</h3><p>Based on the official documentation of Nothing</p><blockquote>You can use Nothing to represent “a value that never exists”: for example, if a function has the return type of Nothing, it means that it never returns (always throws an exception).</blockquote><p>Simply put we usually use Nothing as the return type of a function to indicate that the function always throws an exception.</p><p>Here is the definition of Nothing.</p><pre>public class Nothing private constructor()</pre><p>The above definition means that you cannot instantiate an instance of this class. It also means that no other class can inherit it.</p><p>An example usage ofNothing is in the error function which is part of the Kotlin standard library:</p><pre>public inline fun error(message: Any): Nothing = throw IllegalStateException(message.toString())</pre><p>As can be seen, because the error function always throws an exception, its return type is of type Nothing meaning that this function never completes successfully.</p><h3>Unit</h3><p>The definition of Unit is as follows:</p><pre>public object Unit {<br>    override fun toString() = &quot;kotlin.Unit&quot;<br>}</pre><p>Unit is the same thing as void in Java or C. When the return type of a function is Unit it means the function does not return anything.</p><p>In Kotlin, the default return type of a function is Unit meaning that if you do not specify the return type of a function explicitly then the Kotlin compiler uses Unit as the return type.</p><p>That’s all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0b9779c197" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction to Delegation in Kotlin]]></title>
            <link>https://blog.devgenius.io/a-gentle-introduction-to-delegation-in-kotlin-a1c4f19ec589?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c4f19ec589</guid>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[delegation]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 15:35:37 GMT</pubDate>
            <atom:updated>2022-08-07T20:11:13.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZG5_3kbpEPoh7Mc-eYzmQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@saj_shafique?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Saj Shafique</a> on <a href="https://unsplash.com/s/photos/forward?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In object-oriented programming, delegation is an object-oriented design pattern that works as an alternative to inheritance. In delegation, an object handles a request by delegating it to another object. This other object, that does the real work, is called the delegate.</p><p>As delegation is a design pattern, it means that we can implement it in any object-oriented language. Some object-oriented languages like Kotlin support it natively meaning that there will be no boilerplate code.</p><h3>An Example</h3><p>Let’s go through a rudimentary example to get a basic idea about delegation. First, we define the Software interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b71df6dd695733ebbdc9e3beda2f4f92/href">https://medium.com/media/b71df6dd695733ebbdc9e3beda2f4f92/href</a></iframe><p>Then we define two implementations for the interface we just defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1b23588f2cc13c270bf615b43194ed4/href">https://medium.com/media/e1b23588f2cc13c270bf615b43194ed4/href</a></iframe><p>Now we define a class called WordProcessor that implements the Software interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50ac43c24e4d447722cd572f02a53675/href">https://medium.com/media/50ac43c24e4d447722cd572f02a53675/href</a></iframe><p>WordProcessor receives an instance of Software and when its getLicense is called, it simply delegates/forwards the call to software.</p><p>That’s it! Now you know what delegation is but there is more to it.</p><h3>Class Delegation</h3><p>The example you just saw is an example of class delegation. In class delegation class A delegates some or all of its responsibilities to class B.</p><p>As Kotlin supports class delegation natively, let’s implement the previous example in a more elegant way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d23a76d4b5460a5b492282d8c1b62ff0/href">https://medium.com/media/d23a76d4b5460a5b492282d8c1b62ff0/href</a></iframe><p>The above WordProcessor class has the exact same functionality as the one we defined previously but without any boilerplate code. The Kotlin compiler will generate the boilerplate for us!</p><p>We used the by keyword to let the Kotlin compiler do two things:</p><ol><li>Generating all the methods of the Software interface for WordProcessor.</li><li>Delegating the calls of the generated methods to the corresponding methods of software.</li></ol><p>Decompiling the bytecode of WordProcessor to Java, gives something like the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44626ab71cae14479f5093203f91d5a9/href">https://medium.com/media/44626ab71cae14479f5093203f91d5a9/href</a></iframe><p>The Kotlin compiler has done its job!</p><p>Now it’s time to talk about the other type of delegation which is called property delegation.</p><h3>Property Delegation</h3><p>Before talking about property delegation let’s see why we would need it.</p><h4>An example</h4><p>Consider the following class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472ee2c3fc13e7b5019de57134ac3881/href">https://medium.com/media/472ee2c3fc13e7b5019de57134ac3881/href</a></iframe><p>Imagine we want to implement the following logic for each property of User:</p><ul><li>Print “&lt;property name&gt; is read” when reading the value of the property,</li><li>Print “&lt;property name&gt; is written” when assigning a value to the property.</li></ul><p>So when running the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc491680ee23539216ac5175c689f3f/href">https://medium.com/media/2fc491680ee23539216ac5175c689f3f/href</a></iframe><p>We want to get the output below:</p><pre>firstName is written<br>secondName is written<br>firstName is read<br>secondName is read</pre><p>One naive approach is to manually add println statements when reading/writing any property of User.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42dc8e77a4cb09e6dadcedb09a72fa42/href">https://medium.com/media/42dc8e77a4cb09e6dadcedb09a72fa42/href</a></iframe><p>The above code works but guess what. It’s not scalable at all and we are repeating the same logic. It would be ideal if we could define the logic once and use it without repeating the same logic over and over again. That’s where property delegates could help.</p><h4>Defining a Property Delegate</h4><p>A property delegate is nothing but a class that has very specificgetValue and setValue methods.</p><p>Let’s define a delegate that implements the same logic that we implemented earlier manually.</p><p>Note that for the following code to work we’ll need to add the following dependency to our build.gradle file (assuming we using Gradle of course!)</p><pre><em>implementation</em>(&quot;org.jetbrains.kotlin:kotlin-reflect:&lt;insert version here&gt;&quot;)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53842ef5dc2ac401fb7ac61b9febe385/href">https://medium.com/media/53842ef5dc2ac401fb7ac61b9febe385/href</a></iframe><p>The getValue method is executed when we read the value of the property. It’s an operator method that must have the exact following parameters:</p><ul><li>thisRef must be of type Any?. It’s the instance of the class which contains the delegated property. In case the delegated property is not defined in a class (like being defined in the main function) thisRef will be null.</li><li>property must be of type KProperty&lt;*&gt; or its subtypes. It’s the property itself.</li></ul><p>The return type of getValue must be the same type as the property (or its subtype).</p><p>setValue is the method that gets executed when we assign a value to the property. It’s an operator method that must have the following parameters exactly.</p><ul><li>thisRef has the exact same purpose as described above.</li><li>property has the exact same purpose as described above.</li><li>value is the value being assigned to the property.</li></ul><p>Now we can use the delegate we just defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c488d28236c85d2bc7e210f2416a151e/href">https://medium.com/media/c488d28236c85d2bc7e210f2416a151e/href</a></iframe><p>Running the above code generates the following output.</p><pre>firstName is written<br>secondName is written<br>firstName is read<br>secondName is read</pre><p>Here, again we’re using the by keyword for doing the property delegation. The by keyword tells the Kotlin compiler two things:</p><ol><li>When accessing the value of say firstName, instead of calling the default getter of firstName, call Delegate.getValue.</li><li>When assigning a value to say firstName, instead of calling the default setter of firstName, call Delegate.setValue.</li></ol><p>If we decompile the bytecode of User to Java, we will get the following code which confirms the fact that when setting/getting the value of firstName/lastName, it’s the Delegate that handles the job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe9f0dbd1a9d348d05ed23e82135e887/href">https://medium.com/media/fe9f0dbd1a9d348d05ed23e82135e887/href</a></iframe><p>Note that the delegate we just implemented is a very simple and not-so-useful one. Just use your imagination and think about the things that we can achieve using property delegation.</p><p>This is it! Now you have a basic understanding of delegation in Kotlin.</p><h3>References</h3><p><a href="https://kotlinlang.org/docs/delegation.html">https://kotlinlang.org/docs/delegation.html</a></p><p><a href="https://kotlinlang.org/docs/delegated-properties.html">https://kotlinlang.org/docs/delegated-properties.html</a></p><p><a href="https://www.baeldung.com/kotlin/delegation-pattern">https://www.baeldung.com/kotlin/delegation-pattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c4f19ec589" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-gentle-introduction-to-delegation-in-kotlin-a1c4f19ec589">A Gentle Introduction to Delegation in Kotlin</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Coroutines? Then Keep These in Mind: Part 2 of 2]]></title>
            <link>https://mfallahpour.medium.com/using-coroutines-then-keep-these-in-mind-part-2-of-2-4cda56c824e5?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cda56c824e5</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 11:46:55 GMT</pubDate>
            <atom:updated>2022-08-07T20:31:42.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4lwCKVygIaTLGgb4oRwYw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marusyaionova?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maria Ionova</a> on <a href="https://unsplash.com/s/photos/threads?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When using Kotlin, sooner or later, you come across <a href="https://kotlinlang.org/docs/coroutines-guide.html">coroutines</a>. In two articles we’re going to review the most fundamental things you need to know when using coroutines. This is the second part. You can read the first part <a href="https://mfallahpour.medium.com/using-coroutines-then-keep-these-in-mind-part-1-of-2-5087337712bd">here</a>.</p><p><em>For the rest of this article, I assume that you know the basics of coroutines.</em></p><h3>Cancellation</h3><p>This section is dedicated to a couple of notes about the cancellation behavior of coroutines.</p><h4>Cancellation is cooperative</h4><p>A coroutine has to cooperate to be cancellable. For example, if a coroutine is doing a CPU-intensive task and is not checking for its cancellation it continues its execution even if we call cancel() on its Job.</p><p>The following piece of code depicts a coroutine that cannot be canceled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3d31b27aa6137c3ff3df3e7a09a31c5/href">https://medium.com/media/d3d31b27aa6137c3ff3df3e7a09a31c5/href</a></iframe><p>Running the above code produces the following output.</p><pre>job: I&#39;m sleeping 0 ...<br>job: I&#39;m sleeping 1 ...<br>job: I&#39;m sleeping 2 ...<br>main: I&#39;m tired of waiting!<br>job: I&#39;m sleeping 3 ...<br>job: I&#39;m sleeping 4 ...<br>main: Now I can quit.</pre><p>As can be seen after 1.3 seconds we call job.cancelAndJoin() to cancel the coroutine but the coroutine does not respect the cancellation and continues to print job: I’m sleeping 3 … and job: I’m sleeping 4…</p><p>To make the previous code cancellable we should use the isActive property which is an extension property available inside the coroutine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5007ca07ea7286b695ca1cffad40a2b/href">https://medium.com/media/f5007ca07ea7286b695ca1cffad40a2b/href</a></iframe><p>The only change that we made was to replace while ( i &lt; 5) with while(i &lt; 5 &amp;&amp; isActive). Now if you run the above code the output will be like the following.</p><pre>job: I&#39;m sleeping 0 ...<br>job: I&#39;m sleeping 1 ...<br>job: I&#39;m sleeping 2 ...<br>main: I&#39;m tired of waiting!<br>main: Now I can quit.</pre><h4>Canceling a parent coroutine cancels its children</h4><p>When a parent coroutine is canceled, all its children are canceled too. As an example look at the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff8dee39d14dc4180e11c8948f1cf762/href">https://medium.com/media/ff8dee39d14dc4180e11c8948f1cf762/href</a></iframe><p>Running the above code generates the following output:</p><pre>Canceling the parent coroutine...<br>Parent coroutine cancelled</pre><p>In the above code, we cancel the parent coroutine after starting two child coroutines. This causes the children to be canceled hence no message is printed by them.</p><h4>Canceling a child coroutine does not affect its siblings or its parent</h4><p>When a child coroutine is canceled, it does not affect the execution of its parent or siblings. Look at the following piece of code as an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ba0cbc17973c514f87fc3445eea24b5/href">https://medium.com/media/1ba0cbc17973c514f87fc3445eea24b5/href</a></iframe><p>In the code above, we launch two child coroutines then after a second we cancel the first one. Canceling the first child coroutine has nothing to do with the second child coroutine and the second child continues its execution.</p><p>Running the above code gives the following output:</p><pre>Launching two coroutines...<br>coroutine1: I&#39;m started<br>coroutine2: I&#39;m started<br>coroutine2: I&#39;m done</pre><h3>Exceptions</h3><p>Here, we’re going to talk about a couple of notes about the exception behavior of coroutines.</p><h4>Coroutines throw CancellationException when canceled</h4><p>When a coroutine is canceled it throws a CancellationException. There is no need to use a try/catch to catch this exception (as it’s ignored by the coroutine machinery) unless you want to do something when the coroutine is canceled. Take a look at the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3b4c0ee542ae330c64655567d70ee47/href">https://medium.com/media/b3b4c0ee542ae330c64655567d70ee47/href</a></iframe><p>In the code above, we launch a coroutine then after a second we cancel it. Running the above code generates the following output.</p><pre>Coroutine started.<br>Cancelling the coroutine...<br>Coroutine cancelled.</pre><p>As can be seen, when the coroutine is canceled a CancellationException is thrown which is caught by the try/catch block.</p><p>Removing the try/catch block does not cause the program to crash because as stated earlier, the CancellationException is ignored by the coroutine machinery.</p><h4>Exception in a child coroutine cancels its siblings and parent</h4><p>When a child coroutine throws an exception (other than CancellationException) its siblings (if any) and parent coroutine are canceled altogether.</p><p>Consider the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9df24404954702947058a5126c4f67b8/href">https://medium.com/media/9df24404954702947058a5126c4f67b8/href</a></iframe><p>In the above code, we launch a coroutine with two children. After 500 milliseconds the first child coroutine throws an exception. This cancels both its sibling and parent coroutines.</p><p>If we run the above code we will get the following output.</p><pre>coroutine1 started<br>coroutine2 started<br>coroutine2 canceled<br>Exception in thread &quot;main&quot; java.lang.RuntimeException<br> at ... (omitted for brevity)</pre><p>Based on the above output, the parent and the sibling coroutines did not have the chance to print their respective messages because they got canceled when coroutine1 threw an exception.</p><p>It is possible to change this behavior so that when a child coroutine throws an exception, its sibling(s) and parent coroutines are not canceled. To read about how to implement this behavior take a look at <a href="https://kotlinlang.org/docs/exception-handling.html#supervision">here</a>.</p><p>That’s it for the second and final part.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cda56c824e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Coroutines? Then Keep These in Mind — Part 1 of 2]]></title>
            <link>https://mfallahpour.medium.com/using-coroutines-then-keep-these-in-mind-part-1-of-2-5087337712bd?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/5087337712bd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 08:05:45 GMT</pubDate>
            <atom:updated>2022-08-07T20:28:42.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Coroutines? Then Keep These in Mind — Part 1 of 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4lwCKVygIaTLGgb4oRwYw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marusyaionova?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maria Ionova</a> on <a href="https://unsplash.com/s/photos/threads?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When using Kotlin, sooner or later, you come across <a href="https://kotlinlang.org/docs/coroutines-guide.html">coroutines</a>. In two articles we’re going to review the most fundamental things you need to know when using coroutines. This is the first part. You can read the second part <a href="https://mfallahpour.medium.com/using-coroutines-then-keep-these-in-mind-part-2-of-2-4cda56c824e5">here</a>.</p><p><em>For the rest of this article, I assume that you know the basics of coroutines.</em></p><h3>Basics</h3><p>In this section, we’ll go through a couple of basic good-to-know things about coroutines.</p><h4>Think of coroutines as light-weight threads</h4><p>Coroutines are less resource-intensive compared to threads. When dealing with a handful of coroutines/threads this difference may not be obvious but when dealing with say 100000 them you will witness the difference. Code that exhausts the available memory of JVM when using threads can be expressed using coroutines without reaching the memory limit. For example, the following code launches 100000 coroutines that each wait 3 seconds and then print a message while consuming a reasonable amount of memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440c3cd83f566c0bd8f1bf2eef3f5b03/href">https://medium.com/media/440c3cd83f566c0bd8f1bf2eef3f5b03/href</a></iframe><p>Writing the above piece of code using threads is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ea80f7b3e7fab0b05d363f5a74c879a/href">https://medium.com/media/6ea80f7b3e7fab0b05d363f5a74c879a/href</a></iframe><p>Running the above code consumes too much memory and will probably throw an OutOfMemoryError exception if your machine does not have a huge amount of RAM available.</p><h4>Each coroutine has a scope</h4><p>Each coroutine has a scope (which is of typeCoroutineScope). In other words, you cannot start a coroutine without specifying its scope. The scope determines the lifetime of the coroutine. Also, the scope allows the so-called <a href="https://kotlinlang.org/docs/coroutines-basics.html#structured-concurrency">structured concurrency</a>.</p><p>As an example consider Android’s ViewModel class. A ViewModel has a coroutine scope named viewModelScope and its lifecycle is tied to the ViewModel. Being tied to the ViewModel’s lifecycle means that if you launch coroutines using the viewModelScope and the ViewModel is destroyed then all those coroutines are canceled automatically and there is no need to be worried about resource-wasting, memory leaks, etc.</p><h4>Each coroutine has a context</h4><p>Each coroutine has a context (which is of type CoroutineContext). Coroutine context is a set of elements. Think of the elements as the properties of a coroutine like its name, dispatcher, job, etc. Some of the classes/interfaces that implement CoroutineContext are:</p><ul><li>CoroutineName: User-specified name of coroutine. This name is used when debugging coroutines.</li><li>CoroutineDispatcher: Determines the dispatcher which is used to run the coroutine.</li><li>Job: Provides a couple of useful operations that can be done on a coroutine like canceling it.</li></ul><p>When you create a coroutine you can provide its context. If you do not specify the context of a coroutine, the context will have a default value of EmptyCoroutineContext.</p><p>As an example, the following code creates a coroutine with a custom name and the IO dispatcher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4582fba1c196d395caa9bb47fa722c3c/href">https://medium.com/media/4582fba1c196d395caa9bb47fa722c3c/href</a></iframe><p>Take a look at <a href="https://kt.academy/article/cc-coroutine-context">here</a> if you want to get more familiar with the coroutine context.</p><h4>A coroutine is not bound to a specific thread</h4><p>In general, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one. This means that there is a pool of threads available and at each point in time a potentially different thread from this pool could be responsible for running the coroutine code.</p><p>In order to see this behavior in action, we will use the <a href="https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#unconfined-vs-confined-dispatcher">Unconfined</a> dispatcher. Consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eddcd4a69ef18b306047718f62d80176/href">https://medium.com/media/eddcd4a69ef18b306047718f62d80176/href</a></iframe><p>If we run the above code, the output will be like the following:</p><pre>Before delay. Thread name: main<br>After delay. Thread name: kotlinx.coroutines.DefaultExecutor</pre><p>This means that the coroutine started its execution on a thread named main. Then it got suspended (by calling delay). After suspension, it continued its execution on another thread named kotlinx.coroutines.DefaultExecutor.</p><h3>Parent-child Relationship</h3><p>This section will cover some notes about the parent-child relationship between coroutines.</p><h4>Child coroutines</h4><p>When a coroutine is launched in the scope of another coroutine, the new coroutine becomes the child of the parent coroutine. Take a look at the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5833d93b0f6dde9cae137e59fafa0b61/href">https://medium.com/media/5833d93b0f6dde9cae137e59fafa0b61/href</a></iframe><p>In the above code, we launch two coroutines (child1 and child2) in the scope of another coroutine (parent). This makes child1 and child2 the children of parent. When a coroutine becomes the child of another coroutine a couple of things happen. One such thing is that the child coroutine inherits the CoroutineContext of its parent.</p><h4>Parent coroutine always waits</h4><p>A parent coroutine always waits for the completion of all its children. A parent coroutine does not have to explicitly track all the children it launches, and it does not have to call join() on the Job of each child to wait for their completion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e737dc1cd8e4f0966ae4859f0a41bc3/href">https://medium.com/media/6e737dc1cd8e4f0966ae4859f0a41bc3/href</a></iframe><p>Running the code above gives the following output.</p><pre>Now processing of the request is complete<br>request: I&#39;m done<br>Coroutine 0 is done<br>Coroutine 1 is done<br>Coroutine 2 is done</pre><p>In the above code, we launch 3 coroutines inside the request coroutine. This effectively means that those 3 coroutines become the children of therequest coroutine. In order to wait for all the children to finish we just call request.join() and the request coroutine will wait for all its children to finish.</p><p>That’s it for the first part. You can read the second part <a href="https://mfallahpour.medium.com/using-coroutines-then-keep-these-in-mind-part-2-of-2-4cda56c824e5">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5087337712bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Loopers and Handlers Demystified]]></title>
            <link>https://medium.com/swlh/android-loopers-and-handlers-demystified-481eef1f3984?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/481eef1f3984</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[handler]]></category>
            <category><![CDATA[android-main-thread]]></category>
            <category><![CDATA[android-ui-thread]]></category>
            <category><![CDATA[looper]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 15:25:18 GMT</pubDate>
            <atom:updated>2022-08-08T06:52:49.102Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Loopers and Handlers: The Journey to Implement a Worker Thread.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROPDHaqTZpy5eSeLZjYk_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@amir_v_ali?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">amirali mirhashemian</a> on <a href="https://unsplash.com/s/photos/threads?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this post, I’m going to talk about Loopers and Handlers in Android. Hopefully, after reading this post you’ll know when and how to use them.</p><p>In order to get to know Loopers and Handlers, we are going to implement a worker thread but before that let’s get familiar with the Thread class.</p><h3>Thread</h3><p>Java/Kotlin has a class named Thread which is used to execute some code off the main thread. To use the Thread class we need to do 3 things:</p><ul><li>Create a new class inheriting from Thread</li><li>Override the run method</li><li>Create a new instance of our class and call its start method</li></ul><p>This is how it’s done in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5f4224e467193bfc8c4ebbed908a32/href">https://medium.com/media/6c5f4224e467193bfc8c4ebbed908a32/href</a></iframe><p>After calling start the execution of the thread starts.</p><p>One important note about MyThread is that as soon as run is finished, the thread is destroyed.</p><p>Now suppose that we don&#39;t want our thread to be destroyed when it is done. In other words, when the thread is done with its current task, instead of being destroyed, it waits until another task is available for execution. Basically, we want to have a worker thread.</p><h3>Worker Thread</h3><p>A worker thread has a queue of tasks. When the thread is finished with its current task it picks the next task from the queue and executes it. When the queue of tasks is empty then the thread keeps waiting until a task is available to execute.</p><p>What we’re going to do is to implement a worker thread in three different ways. From the most cumbersome to the most elegant!</p><h3>Handcrafted Worker Thread</h3><p>In order to implement a worker thread from scratch, using the Thread class, we need to do a couple of things:</p><ul><li>Putting an infinite loop inside the run method</li><li>Creating a queue for keeping track of the tasks to execute</li><li>Inside the infinite loop, we get the next task from the queue and execute it</li><li>Find a way to break out of that infinite loop so that we can stop the worker thread when we are done.</li></ul><p>The following code does all of the above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4209befd8af2659da96eb191b5439a33/href">https://medium.com/media/4209befd8af2659da96eb191b5439a33/href</a></iframe><p>To add a task to the queue of the worker thread we call execute. Calling quit finishes the worker thread. We can use the HandcraftedWorkerThread like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef4da0479aed8377a6c258882093cd15/href">https://medium.com/media/ef4da0479aed8377a6c258882093cd15/href</a></iframe><p>Our worker thread works but it has two problems:</p><ol><li>When there is no task to execute, the while loop inside the run method is constantly checking the value of isAlive. This is <a href="https://en.wikipedia.org/wiki/Busy_waiting">busy waiting</a> and as we all know we are wasting CPU cycles.</li><li>We are doing too much work to implement a worker thread! Actually not too much really but we can avoid things like managing the queue of tasks ourselves.</li></ol><p>Now it’s time for a better implementation of a worker thread.</p><h3>Looper Worker Thread</h3><p>Before implementing the second version of our worker thread we need to get familiar with two classes.</p><h4>Looper</h4><p>Looper class does two things:</p><ol><li>It converts an ordinary thread (which is destroyed when its run method is finished) to a thread that can stay alive as long as the Android app is alive.</li><li>It has a queue of tasks to execute.</li></ol><h4>Handler</h4><p>We can not directly add a task to the queue of a Looper. Instead, we should use an instance of a Handler to do the trick. In other words, we use a Handler to add a task to the queue of a Looper.</p><p>Now we can implement the second version of our worker thread using a Looper and a Handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/192a6560e99c1936d779e5542bddae10/href">https://medium.com/media/192a6560e99c1936d779e5542bddae10/href</a></iframe><p>A couple of notes about the above implementation:</p><ul><li>To convert an ordinary thread to a thread that can run forever we need to call Looper.prepare() and then Looper.loop(). Also, prepare should always be called after the start method of the thread. Otherwise, it will throw an exception.</li><li>To communicate with the queue of the Looper we have created an instance of Handler and passed the Looper of the current thread to the Handler.</li><li>To add a task to the queue of the Looper we call Handler.post() and pass it a Runnable.</li><li>When we are done with the worker thread we should call the quit method to stop its associated Looper.</li></ul><p>We can use the LooperWorkerThread just like how we did with the HandcraftedWorkerThread.</p><p>With this implementation, we eliminated the busy waiting and also got rid of manually managing the queue of tasks.</p><p>We can still do better than this! Here is how.</p><h3>Handler Worker Thread</h3><p>To create a worker thread we can inherit from HandlerThread instead Thread. This makes things a lot easier. The reason is that HandlerThread has an inner Looper so we don&#39;t need to create one manually.</p><p>What follows is the implementation of a worker thread using a HandlerThread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b26e17796d0ab52660390bc79f96842/href">https://medium.com/media/0b26e17796d0ab52660390bc79f96842/href</a></iframe><p>Some notes about the code above:</p><ul><li>As stated earlier, because HandlerThread has an inner Looper there is no need to create one explicitly.</li><li>To communicate with the Looper of HandlerThread we have created a Handler. Note that when we create an instance of Handler without passing a Looper to its constructor, the Handler implicitly uses the Looper of the current thread. Here, the Handler will be associated with the Looper of the HandlerThread.</li><li>We do a check inside execute to make sure that handler is initialized before calling its post method. The reason is that this way we prevent a runtime error if, by any chance, execute is called before onLooperPrepared callback is called.</li><li>We have created the Handler inside the onLooperPrepared method. The reason is that we should create the Handler only when the Looper is prepared. When the Looper of HandlerThread is prepared the onLooperPrepared is called and that’s where we instantiate the Handler.</li></ul><p>And this is it. Just compare HandlerWorkerThread with HandcraftedWorkerThread to appreciate what we achieved!</p><h3>The Main Thread of an Android App</h3><p>Now that we know about Loopers and Handlers we can talk a little bit about the main thread of an Android app. This thread is also called the UI thread as well.</p><p>Each Android app has a single main thread. The main duty of this thread is handling the user’s interactions with the app like clicking a button, rendering a list of items, and so on.</p><p>Suppose that the main thread is an ordinary thread. One that gets destroyed when its run method is finished. The user starts the app, the main thread starts executing, the UI of the first screen of the app is displayed and the main thread is destroyed!</p><p>Does that sound weird? Yes! Because that’s not what happens in reality. What actually happens is that the main thread is alive as long as the app is alive. So the main thread of an Android app is not an ordinary thread. It’s a <em>worker thread</em>. You see, it’s a worker thread!</p><p>Because the main thread of an Android app is a worker thread that means it has a Looper associated with it and there is a queue of tasks. All interactions of the user with the app like clicking a button, scrolling a list, and so on are added as a task to the queue of the main thread and are executed one by one.</p><p>Congrats! By now you should have a good grasp of Loopers, Handlers, and worker threads.</p><p>You can access the source code of this post from the following link.</p><p><a href="https://github.com/MasoudFallahpour/AndroidWorkerThread">GitHub - MasoudFallahpour/AndroidWorkerThread: This is the accompanying source code of my post on Medium about Android&#39;s Loopers and Handlers.</a></p><h3>References</h3><ul><li><a href="https://blog.mindorks.com/android-core-looper-handler-and-handlerthread-bd54d69fe91a">https://blog.mindorks.com/android-core-looper-handler-and-handlerthread-bd54d69fe91a</a></li><li><a href="https://www.youtube.com/playlist?list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2">https://www.youtube.com/playlist?list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=481eef1f3984" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/android-loopers-and-handlers-demystified-481eef1f3984">Android Loopers and Handlers Demystified</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with Kotlin: Creating a DSL for Constructing Binary Trees]]></title>
            <link>https://mfallahpour.medium.com/fun-with-kotlin-creating-a-dsl-for-constructing-binary-trees-6295bcb1902d?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/6295bcb1902d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-dsl]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 19:52:48 GMT</pubDate>
            <atom:updated>2024-02-15T19:04:32.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBAg0d3cxm2b-_X8W8_1Ow.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glt23?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gilly Tanabose</a> on <a href="https://unsplash.com/s/photos/tree-branch?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this post, we’re going to implement a DSL for constructing <a href="https://en.wikipedia.org/wiki/Binary_tree#:~:text=In%20computer%20science%2C%20a%20binary,child%20and%20the%20right%20child.&amp;text=It%20is%20also%20possible%20to,is%20an%20ordered%2C%20rooted%20tree.">binary trees</a> declaratively. We will not jump directly to the DSL implementation but rather start with the most meticulous (and unreadable) approach and gradually move towards our DSL. Let’s start!</p><p>For the rest of this article, we use the following binary tree as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*LTUgJYtClrTJ8zcou-cGag.png" /></figure><h3>First Approach</h3><p>The first thing we need is to define the class for a binary tree node. We can do it like this:</p><pre>class BinaryTreeNode&lt;T&gt;(<br>    var value: T,<br>    var left: BinaryTreeNode&lt;T&gt;? = null,<br>    var right: BinaryTreeNode&lt;T&gt;? = null<br>)</pre><p>Now we can write the following code to create a binary tree.</p><pre>fun main() {<br>    val root = BinaryTreeNode(&quot;A&quot;)<br>    val b = BinaryTreeNode(&quot;B&quot;)<br>    val c = BinaryTreeNode(&quot;C&quot;)<br>    val d = BinaryTreeNode(&quot;D&quot;)<br>    val e = BinaryTreeNode(&quot;E&quot;)<br>    val f = BinaryTreeNode(&quot;F&quot;)<br><br>    root.left = b<br>    root.right = c<br><br>    b.left = d<br>    b.right = e<br><br>    c.right = f<br>}</pre><p>As can be seen, not readable at all! When someone looks at the above code they should carefully follow the code to be able to have an idea of the structure of the tree.</p><h3>Second Approach</h3><p>For our second approach, we use apply <a href="https://kotlinlang.org/docs/scope-functions.html">scope function</a> to make our tree construction code more readable. We can write a code like the following.</p><pre>fun main() {<br>    val root = BinaryTreeNode(&quot;A&quot;).apply {<br>        left = BinaryTreeNode(&quot;B&quot;).apply {<br>            left = BinaryTreeNode(&quot;D&quot;)<br>            right = BinaryTreeNode(&quot;E&quot;)<br>        }<br>        right = BinaryTreeNode(&quot;C&quot;).apply {<br>            right = BinaryTreeNode(&quot;F&quot;)<br>        }<br>    }<br>}</pre><p>It’s obvious that this approach is far more readable than our previous approach. For instance, we can easily see that nodes “D” and “E” are the left and right children of node “B” respectively.</p><p>To make the above code a bit more readable we can define a small function node to create a new instance of BinaryTreeNode. Using the node function, we will end up with the following code.</p><pre><br>fun main() {<br>    val root = node(&quot;A&quot;).apply {<br>        left = node(&quot;B&quot;).apply {<br>            left = node(&quot;D&quot;)<br>            right = node(&quot;E&quot;)<br>        }<br>        right = node(&quot;C&quot;).apply {<br>            right = node(&quot;F&quot;)<br>        }<br>    }<br>}<br><br>fun &lt;T&gt; node(value: T) = BinaryTreeNode(value)</pre><p>The change we made was a small one but it helped to have a slightly more readable code.</p><h3>Using a DSL</h3><p>So far we have seen two approaches to create a binary tree. Now it’s time to create our own DSL for creating such a tree. What we want to achieve is like the following code.</p><pre>fun main() {<br>    val root = binaryTree(&quot;A&quot;) {<br>        left(&quot;B&quot;) {<br>            left(&quot;D&quot;)<br>            right(&quot;E&quot;)<br>        }<br>        right(&quot;C&quot;) {<br>            right(&quot;F&quot;)<br>        }<br>    }<br>}</pre><p>In the next section, we will see how we can implement such a DSL for creating binary trees.</p><h3>Implementing the DSL</h3><p>We will start with defining a function named binaryTree which we can call to start creating a tree.</p><pre>fun &lt;T&gt; binaryTree(rootValue: T, content: BinaryTreeBuilder&lt;T&gt;.() -&gt; Unit = {}): BinaryTreeNode&lt;T&gt; {<br>    val root = BinaryTreeNode(rootValue)<br>    val binaryTreeBuilder = BinaryTreeBuilder(root)<br>    binaryTreeBuilder.content()<br>    return root<br>}</pre><p>Let’s see what the above function does. The first parameter of binaryTree is the value of the tree root. The value of a node could be of any type (Int, String, custom classes, you name it). The second parameter is a <a href="https://kotlinlang.org/docs/lambdas.html#function-literals-with-receiver">lambda with receiver</a> (we will talk about the BinaryTreeBuilder later on). The return value of the function is the root of the binary tree.</p><p>In the body of the binaryTree function we do several things:</p><ul><li>Create the root node of the binary tree (root).</li><li>Create a new instance of BinaryTreeBuilder and pass root to its constructor.</li><li>Call the content lambda on the BinaryTreeBuilder instance</li><li>Return the root node as the root of the binary tree</li></ul><p>Using Kotlin’s trailing lambda syntax, we can call the above function like below:</p><pre>binaryTree(&quot;A&quot;) {<br>}</pre><p>Inside the lambda is where we can start adding nodes to the tree. The lambda has a receiver with typeBinaryTreeBuilder that allows adding nodes to the tree.</p><p>Let’s see the implementation of BinaryTreeBuilder.</p><pre>class BinaryTreeBuilder&lt;T&gt;(root: BinaryTreeNode&lt;T&gt;) {<br>    private var currentParent = root<br><br>    fun left(value: T, content: () -&gt; Unit = {}) {<br>        val parent = currentParent<br>        val newNode = BinaryTreeNode(value)<br>        parent.left = newNode<br>        currentParent = newNode<br>        content()<br>        currentParent = parent<br>    }<br><br>    fun right(value: T, content: () -&gt; Unit = {}) {<br>        val parent = currentParent<br>        val newNode = BinaryTreeNode(value)<br>        parent.right = newNode<br>        currentParent = newNode<br>        content()<br>        currentParent = parent<br>    }<br>}</pre><p>Let’s see how the above code works.</p><p>Looking at the above code we can see that, at any given time, currentParent keeps track of the current node that we want to add a node to it as its child.</p><p>There are also two methods left and right that is used to add a left and a right node as the children of the current node respectively. Let’s see how function left works:</p><ul><li>A new node (newNode) is created and set as the left child of the current parent node (currentParent),</li><li>Temporarily newNode is set as the new current parent and the content lambda executes. This effectively causes whatever nodes added in the lambda to be the children of newNode.</li><li>After executing the content lambda currentParent is restored to its previous value.</li></ul><p>The right function works in a similar way except that newNode is added as the right child of currentParent.</p><p>That’s it. Our DSL is ready to use!</p><h3>Where I use this DSL</h3><p>Every once in a while I spend some time solving LeetCode problems. When the problem is a binary tree one, after implementing the algorithm I need to create some binary trees as test cases to test my algorithm against them. I use the DSL we just developed to easily create those test cases!</p><p>You can access the source code of this post from <a href="https://github.com/MasoodFallahpoor/BinaryTreeDsl">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6295bcb1902d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Notes Regarding Writing UI Tests for Jetpack Compose Layouts]]></title>
            <link>https://mfallahpour.medium.com/some-notes-regarding-writing-ui-tests-for-jetpack-compose-layouts-efb13066bb3d?source=rss-78bfa2974575------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb13066bb3d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack-compose-testing]]></category>
            <dc:creator><![CDATA[Masoud Fallahpour]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 10:04:55 GMT</pubDate>
            <atom:updated>2022-11-03T20:47:36.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykmxJf4um8BdERjGRPpw6w.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@girlwithredhat">Girl with red hat</a> on <a href="https://unsplash.com/photos/ZOdMHFZ0HkM">Unsplash</a></figcaption></figure><p><a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a> (from now on Compose) is Android’s modern toolkit for building native UIs declaratively. It simplifies and accelerates UI development.</p><p>Compose is stable now and thanks to that, a lot of companies and developers are going to use it, if not using it already!</p><p>When using Compose, sooner or later, you’ll come to the point when you start writing UI tests to verify the behavior of your layouts.</p><p>What follows are my thoughts and findings regarding writing UI tests for Compose layouts.</p><p><em>For the rest of this article, I assume that you know the basics of writing UI tests for Compose layouts.</em></p><p>As an experiment and for getting my feet wet with Compose, I started to migrate the UI of <a href="https://github.com/MasoodFallahpoor/ReleaseTracker">ReleaseTracker</a> from the (classic!) View system to Compose. After implementing the UI of the app, I started to write UI tests, and here are my notes regarding writing UI tests for Compose layouts:</p><ol><li>Lack of enough documentation,</li><li>Finding composables is sometimes cumbersome,</li><li>Passing true to useUnmergedTree argument,</li><li>You still need Espresso.</li></ol><p>In the following sections, I will elaborate on the aforementioned notes.</p><h3>Lack of Enough Documentation</h3><p><a href="https://developer.android.com/jetpack/compose/documentation">Official documentation</a> of Compose is extensive with a pathway, lots of codelabs, and reference documentation. When it comes to testing there are three resources:</p><ol><li><a href="https://developer.android.com/jetpack/compose/testing">Testing</a></li><li><a href="https://developer.android.com/jetpack/compose/testing-cheatsheet">Testing cheat sheet</a></li><li><a href="https://developer.android.com/codelabs/jetpack-compose-testing#0">Testing codelab</a></li></ol><p>Although the above documentations and the codelab can help you get started with testing they quickly fall short when you start to write UI tests for a real-world app.</p><p>In order to comprehend the shortage of documentation, you can compare it with the volume of documentation available for Espresso. Espresso docs cover almost everything you need to write UI tests.</p><p>When writing UI tests for Compose layouts, I often found myself searching on the Internet to see how to get things done.</p><h3>Finding Composables Is Sometimes Cumbersome</h3><p>In the View system, each view can have an ID, and using that, you can easily find them in your UI tests. In Compose, composables have no such thing and that makes finding them hard, if not impossible.</p><p>As an example, look at the following code:</p><pre>Column <strong>{<br>    </strong>Text(text = &quot;Hello Compose!&quot;)<br>    Text(text = &quot;Hello Compose!&quot;)<br><strong>}</strong></pre><p>In the above code, there is no way to find the first Text composable in a test; in order to perform an action on it or assert something about it.</p><p>There are two ways to circumvent this problem:</p><ul><li>Test tags,</li><li>Combining matchers.</li></ul><h4>Test Tags</h4><p>Think of a test tag as an ID! The name is different but can serve the same purpose: finding composables easily.</p><p>To set a test tag for a composable we can use the semantics modifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a471dfffe51c35f06d2a746c3c09c7c/href">https://medium.com/media/2a471dfffe51c35f06d2a746c3c09c7c/href</a></iframe><pre>composeRule.onNodeWithTag(&quot;text1&quot;).assertTextEquals(&quot;Hello Compose!&quot;)</pre><p>Using test tags is easy but it has the following drawbacks:</p><ul><li>It pollutes the production code. By that, I mean these tags have no use other than enabling you to test your UI.</li><li>There is no help from the IDE for detecting duplicate test tags. If you use the same ID for two views in an XML layout, then Android Studio raises an error. There is no such support for Compose and you should double-check all test tags, in the composable under test, to be unique.</li></ul><h4>Combining Matchers</h4><p>The <a href="https://developer.android.com/jetpack/compose/testing#setup">testing libraries</a> provided by Compose have different matchers for finding composables. Sometimes a single matcher is not enough to find a composable. Instead, a combination of them should be used to find the desired composable.</p><p>To demonstrate how we can combine matchers to find a composable consider the following piece of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e0b73c9fc050856ae7374548adf55cb/href">https://medium.com/media/5e0b73c9fc050856ae7374548adf55cb/href</a></iframe><p>The above code displays a list of three countries. Previewed in Android Studio, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbKjou1LzXFV9bd_SFaq-Q.png" /></figure><p>Now suppose that we want to write a UI test for ListOfCountries composable and assert that the checkbox next to “Iran” is checked.</p><p>Using test tags here does not help. If we assign a test tag (for instance “CountryCheckbox”) to the Checkbox composable then we will have three checkboxes with the same test tag and cannot distinguish them in tests. We will combine matchers to find the desired composable.</p><p>In order to find the desired Checkbox composable we should:</p><ul><li>Find the Text composable with text “Iran”. Call this composable X,</li><li>From all the sibling composables of X find the composable which is toggleable.</li></ul><p>The following compound matcher does it for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68b3f468a4c5a938e7713bcbd0abef27/href">https://medium.com/media/68b3f468a4c5a938e7713bcbd0abef27/href</a></iframe><p>Now by using the above matcher we can assert that the checkbox next to “Iran” is checked (or is on).</p><pre>composeRule.onNode(isToggleableWithSiblingText(&quot;Iran&quot;))<br>    .assertIsOn()</pre><h3>Passing ‘true’ to ‘useUnmergedTree’ Argument</h3><p>When building layouts in Compose, the composables form a tree data structure. In addition to this tree, there is another tree, the <a href="https://developer.android.com/jetpack/compose/semantics">semantics</a> tree. The semantics tree describes your UI in such a way that it is understandable for accessibility services and for the testing framework. The testing framework uses this tree to find nodes, interact with them, and make assertions.</p><p>For several tests that I was writing, they kept failing with the following error although everything seemed correct.</p><pre>java.lang.AssertionError: Failed to assert the following: ...<br>Reason: Expected exactly &#39;1&#39; node but could not find any node that satisfies: ...</pre><p>The above error means that a composable that I wanted to assert about it could not be found. After digging a bit, I found that passing true to useUnmergedTree argument made them all pass. So instead of the following line</p><pre>composeRule.onNodeWithText(&quot;Hello&quot;).assertIsDisplayed()</pre><p>I used</p><pre>composeRule.onNodeWithText(&quot;Hello&quot;, useUnmergedTree = true)<br>    .assertIsDisplayed()</pre><p>The reason is that, by default, finders like onNode, onNodeWithText, etc. use the merged semantics tree. In a merged semantics tree some nodes may merge with each other forming a single node. This may cause some composables not to be found.</p><h3>You Still Need Espresso</h3><p>Although <a href="https://developer.android.com/training/testing/espresso">Espresso</a> is primarily for testing the UIs implemented with the View system, that does not mean you don’t need it when testing Compose layouts.</p><p>As an example, I wanted to dismiss a dialog in one of my tests. The testing artifacts of Compose did not provide a means to do so. After a bit of struggling, I found that using Espresso.pressBack() does the trick.</p><p>As another example, I wanted to test if the correct Intent is sent when a particular action is performed. Once again Espresso came to the rescue with its powerful validation and stubbing API for Intents.</p><p><em>That’s all I think! Thanks for taking the time to read this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb13066bb3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>