jambit ToiletPaper 112

Kotlin Coroutines


Certain actions should run in the background to avoid blocking the main thread of the app. Typically threads or AsyncTasks are used for this: the action runs in the background, and finally the result is displayed on the main thread.


Kotlin offers a more elegant way with coroutines. Coroutines are lightweight threads that are dispatched to a Kotlin-managed thread pool if you use existing dispatchers. This is comparable with GCD from iOS.


An image should be downloaded and displayed:

private fun downloadImageWithCoroutines() {
    GlobalScope.launch(Dispatchers.Main) {
        binding.status.text = "Downloading image ..."
        // Download the image on an IO dispatcher without blocking the main thread
        val image = withContext(Dispatchers.IO) { downloadImage() }
        // Continue on the main thread

In the example above, the status is first set on the main thread, followed by an asynchronous download of the image. The special thing about this is that the main thread is not blocked, but only when the result is available the rest of the code continues to run on the main dispatcher.

Technically, Kotlin solves this by executing the code as continuation after withContext. This enables you to rewrite the downloadImage method so that it passes the result to a continuation and does not return it directly. Of course the caller of the method has to take care of the threading:

private fun downloadImage(continuation: (Drawable?) -> Unit) {
    val drawable = url.openStream()?.use {
        Drawable.createFromStream(it, "image")

A special strength is the combination of several async calls. The async calls can be executed simultaneously on different IO threads:

// Start multiple requests
val image1 = async(Dispatchers.IO) { downloadImage1() }
val image2 = async(Dispatchers.IO) { downloadImage2() }
// Wait for the results and show the images

Further Aspects


Author: Marco Pfattner / Senior Software Architect/ Business Division Automotive Bavaria

Download Toilet Paper #112: Kotlin Coroutinen (pdf)

Kotlin Coroutines jambit ToiletPaper

Cookie Settings

This website uses cookies to personalize content and ads, provide social media features, and analyze website traffic. In addition, information about your use of the website is shared with social media, advertising, and analytics partners. These partners may merge the information with other data that you have provided to them or that they have collected from you using the services.

For more information, please refer to our privacy policy. There you can also change your cookie settings later on.

contact icon

Contact us now