<?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 Milan Bárta on Medium]]></title>
        <description><![CDATA[Stories by Milan Bárta on Medium]]></description>
        <link>https://medium.com/@milanbarta?source=rss-4222cb1d4f17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k8m4g68H-V6TeO-4lmxv-Q.jpeg</url>
            <title>Stories by Milan Bárta on Medium</title>
            <link>https://medium.com/@milanbarta?source=rss-4222cb1d4f17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:58:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milanbarta/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 Coroutines in Android]]></title>
            <link>https://sourcediving.com/kotlin-coroutines-in-android-e2d5bb02c275?source=rss-4222cb1d4f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2d5bb02c275</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Milan Bárta]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 07:58:32 GMT</pubDate>
            <atom:updated>2018-04-16T08:26:51.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmJcVenlKgKqo0GZPG9iFA.png" /></figure><p>Handling concurrency on Android has always been challenging. However, with the increasingly popular adoption of Kotlin for Android development, new possibilities of writing asynchronous code, such as coroutines, arise.</p><p>In this blogpost, after a brief introduction of what coroutines are and how they work internally, we’re going to look at a few practical examples of using coroutines to write an easy-to-read asynchronous code for Android.</p><h3>Coroutines in Kotlin</h3><p>The concept of coroutines has been introduced in Kotlin version 1.1. At this moment, they’re still an experimental feature of the language and the internal implementation is quite likely to change.</p><p>Coroutines are essentially a light-weight alternative to threads. They allow running an asynchronous piece of code in the same manner as you’d normally run a synchronous one. This eliminates having to deal with complicated and verbose syntax when writing concurrent code, which is so typical when dealing with applications in Java and other programming languages.</p><p>Coroutines in the Kotlin language are implemented on the lowest possible level, allowing other libraries to build upon the language-provided APIs. At the same time, a higher-level coroutine language constructs, such as async and await pattern, are provided by the Kotlin coroutine library.</p><p>Existing implementations are available in form of libraries building upon <em>RxJava</em>, <em>CompletableFuture</em>, <em>NIO</em>, <em>Swing</em>, <em>Android</em>, etc. All of them can be found in the kotlinx.coroutines library (<a href="https://github.com/Kotlin/kotlinx.coroutines">GitHub page</a>).</p><h3>Coroutines internals</h3><p>Coroutines in Kotlin are typically very light-weight and the way they’re compiled doesn’t depend on an operating system. Essentially, every suspending function is transformed by the compiler into a state machine with states representing suspend calls.</p><p>Right before a suspension call, the next state is stored in a field of a compiler-generated class along with relevant context. Resuming from suspension restores the saved state and the state machine continues from the point after the suspension call. A suspended coroutine can also be passed around as an object of Continuation type containing its state and local context.</p><p>This allows starting hundreds of thousands of coroutines at the same time as opposed to limitations of working with threads which are quite expensive to use in comparison. A popular example shows a code starting a <em>100,000 </em>coroutines and starting the same number of threads. The coroutine example would normally run just fine, while starting such a large number of threads would most likely crash your app with an OutOfMemory error.</p><h3>Coroutines in Android</h3><p>Enabling Kotlin coroutines in Android involves just a few simple steps. First of all, add the Android coroutine library dependency into your build.gradle project file.</p><pre>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:0.22.5&quot;</pre><p>As coroutines are still considered an experimental feature in the current version of Kotlin (version 1.2.30 at the time of writing), you will need to add the following line to your gradle.properties, otherwise you’ll see a warning in the compiler output.</p><pre>kotlin.coroutines=enable</pre><p>In the following sections, we’re going to look into writing our own suspending functions, processing results from suspending functions on the UI thread, handling exceptions in coroutines, and limiting coroutine execution to lifecycle of Android components.</p><h4>Your first suspending function</h4><p>A suspending function is just a regular Kotlin function with an additional suspend modifier which indicates that the function can suspend the execution of a coroutine. Suspending functions can invoke any other regular functions, but to actually suspend the execution, it has to be another suspending function.</p><p>On the other hand, a suspending function cannot be invoked from a regular function, therefore several so-called coroutine builders are provided, which allow calling a suspending function from a regular non-suspending scope.</p><p>The Kotlin coroutine library provides several coroutine builders:</p><ul><li>runBlocking: launches a new coroutine and <strong>blocks</strong> current thread until its completion,</li><li>launch: launches a new coroutine and returns a reference to it as a Job object which doesn’t have a result value associated with it,</li><li>async: launches a new coroutine and returns a reference to it as a Deferred&lt;T&gt; object which allows returning a value from it (also store an exception). It has to be used together with await suspending function which waits for the result without blocking the thread.</li></ul><p>Let’s demonstrate some of the theory we’ve learned so far on a simple real-world example. Following excerpt of code causes that tapping the FAB should change the text on screen after a defined delay without blocking the thread it’s running on while waiting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dedea52ca8127784724f5e8a52c40c7c/href">https://medium.com/media/dedea52ca8127784724f5e8a52c40c7c/href</a></iframe><p>So what happened here? In an OnClickListener we’re using the launch coroutine builder and passing in the UI of CoroutineDispatcher type, as a parameter to it. The UI parameter makes sure the block of code is run on the main thread.</p><p>Inside the launch block, we’re invoking our suspending function setTextAfterDelay which is defined below. Inside our suspending function, another suspending function delay is invoked, which delays the coroutine without blocking a thread. After the defined time passes, the function continues its execution and sets the text to the TextView.</p><h4>Processing results on the main thread</h4><p>As Android only allows accessing the view hierarchy from the original thread that created them (usually the main thread), coroutines come with an option to specify the thread to run on by passing the CoroutineDispatcher to a coroutine builder.</p><p>Kotlin coroutine library provides several dispatchers, e.g. CommonPool (which confines coroutine execution to a pool of background threads) or newSingleThreadContext (which creates a new single-threaded coroutine context). If none is specified, the DefaultDispatcher is used (it is equal to CommonPool, but can change in the future, so it’s recommended to always specify it explicitly).</p><p>We already know the UI CoroutineDispatcher provided for running coroutine code on the Android main thread from the previous example.</p><p>Let’s have a look at the following piece of code that demonstrates executing a network call on a background thread and displaying the result on the main thread using a simple coroutine syntax.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09804fe2d579eb13e24e1ca3cd938bcf/href">https://medium.com/media/09804fe2d579eb13e24e1ca3cd938bcf/href</a></iframe><p>Same as in the previous example, we’re using launch coroutine builder with the UI CoroutineDispatcher to start a coroutine. Inside it, an async launcher is invoked together with the await suspending function waiting for the expected result of network call.</p><p>The async code block invokes a regular function downloadDataBlocking which, as the name suggests, downloads a JSON string from the network in a blocking way. This is OK though, because we’re confining the async block to a shared pool of background threads by passing CommonPool as parameter to it. This way, the main thread is not blocked during the network call execution.</p><p>The returned result of the network call is immediately passed in to a TextView on the main thread.</p><h4>Handling exceptions</h4><p>The previous example makes handling network calls simple and allows us to write code in a sequential manner without the need to think about threading too much.</p><p>That’s just an ideal case though. What would happen if an error occurred during the execution? As with any unhandled exception, the application would normally crash.</p><p>The following example code demonstrates how coroutines make handling exceptions easy. As with traditional non-concurrent code, simply wrapping calls in a try/catch block does the job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d98c31ba9a463796e260a9d9e354a86/href">https://medium.com/media/2d98c31ba9a463796e260a9d9e354a86/href</a></iframe><h4>Callback wrapping</h4><p>Handling asynchronous code execution usually involves implementing some sort of callback mechanisms. For example, with an async network call, you probably want to have an onSuccess and onFailure callbacks so that you can handle the two cases appropriately.</p><p>Such code can often become quite complex and hard to read. Luckily, coroutines provide a way to wrap callbacks to hide the complexity of the asynchronous code handling away from the caller.</p><p>Let’s have a look at an example of asynchronous network call with a callback for handling the result. We’re going to wrap the callback in a coroutine and simplify the network call significantly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71f7ca9dc6c830d4383658cb2eae39b0/href">https://medium.com/media/71f7ca9dc6c830d4383658cb2eae39b0/href</a></iframe><p>As in the previous examples, we start our coroutine with launch, passing in the UI CoroutineDispatcher. Inside, we’re invoking our suspending function downloadDataAsync we’ve defined a few lines below.</p><p>Notice that our suspending function returns the result of a suspendCoroutine suspending function provided by the coroutine library. It captures the current Continuation instance and suspends currently running coroutine.</p><p>The Continuation object provides two functions we can resume the coroutine execution with. Invoking resume resumes the coroutine execution and returns a value, while resumeWithException re-throws the exception right after the last suspension point.</p><h4>Cancelling a coroutine</h4><p>As with any multi-threading concept, the lifecycle of Android components can become a problem. We need to stop any potentially long-running background tasks when an Activity (or Fragment) reaches certain lifecycle events (typically onStop or onDestroy) in order to prevent memory leaks or crashes when the result becomes available after the Activity has been destroyed.</p><p>To resolve this, coroutines provide a simple cancelling mechanism. When a new coroutine is launched using a coroutine builder, an instance of a Job object is returned, representing the running coroutine.</p><p>In order to cancel a coroutine, simply call the cancel method on the Job object returned from the coroutine builder. There is also a join method available which suspends the coroutine execution until the cancelled job is complete. For convenience, a cancelAndJoin method combining the two is also provided.</p><p>Coroutine cancellation is cooperative. That means that the suspending function has to cooperate in order to support cancelling. In practice, the suspending function has to periodically test the isActive property which is set to false when the coroutine is cancelled.</p><p>This applies to your suspending functions though. All suspending functions provided by the Kotlin coroutine library support cancellation already.</p><p>The following piece of code shows an example of a non-blocking counter increasing its value every second. The counter can be cancelled by tapping the FAB.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71344460903f09f2f55515535c2b3b6e/href">https://medium.com/media/71344460903f09f2f55515535c2b3b6e/href</a></iframe><h3>Conclusion</h3><p>Coroutines allow us to write concurrent code in a traditional imperative manner without having to worry too much about threading, handling callbacks or exceptions.</p><p>Learning the basic concepts in order to start using coroutines is, when compared to other commonly used libraries like RxJava, very easy. On the other hand, if you already know RxJava and use it extensively in your codebase, you’ll probably see no reason to switch to coroutines as you would lose the fine control over threading and a huge collection of functional operators RxJava offers.</p><p>All in all, coroutines seem like a nice and simple approach for writing asynchronous code on Android, especially for developers who are not familiar with RxJava or don’t want to use RxJava or similar library in their projects. If you haven’t tried them, give them a go and let me know in the comments what you think.</p><p>In this article, we’ve only scratched the surface of what coroutines are and how to use them. For more in-depth information, refer to an <a href="https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md">informal coroutine description document</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2d5bb02c275" width="1" height="1" alt=""><hr><p><a href="https://sourcediving.com/kotlin-coroutines-in-android-e2d5bb02c275">Kotlin Coroutines in Android</a> was originally published in <a href="https://sourcediving.com/">Source Diving</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>