Kotlin Coroutines Tutorial (STABLE VERSION) – async / await, withContext, launch

With Kotlin 1.3 we finally have a stable library for coroutines. This means that there won’t be any breaking changes to the API. Now is an especially good time to learn how to use them.

Coroutines are basically light-weight, much more efficient threads. As a bonus, they are extremely easy to work with once you know the basics. Asynchronous coroutine code looks the same as a classic synchronous code. You don’t need to learn any new programming paradigms in order to use Kotlin’s coroutines.

In this tutorial you are going to learn quite a bit about coroutines – different ways of launching them, blocking versus non-blocking code and async / await.

?Get the code from this tutorial?

Or get the code here:

 

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.


Will

2 months ago

Hi, I saw the tutorial. It is awesome. I already commented in youtube (arkorott) and recommended your tutorial on stack overflow.

But I am still stuck. I realized that by doing this in the code below, I was creating a new thread but still blocking the main thread.

fun getCrimes(): ArrayList = runBlocking(Dispatchers.Default) {
val result = async { crimesDAO.getAllCrimes() }.await()
[email protected] result as ArrayList
}

How do I have a coroutine run on a separate thread but get the result back on the main thread when finished?
I asked this on Stack Overflow but have not yet solved it:

https://stackoverflow.com/questions/52746866/android-room-kotlin-query-in-background-thread-return-value-problem/52752174#52752174

Any help much appreciated !!
Thanks

Matej Rešetár

2 months ago

Did you resolve your issue with what I wrote you on YouTube?

Will

2 months ago

Not yet. Question.
If for example I make a suspend function like this:

suspend fun retrieveCrimes(): List {
return crimesDAO.getAllCrimes() // This is the actual call to the DAO
}

How can I call it without blocking the main thread. What I tried (copied below) creates a new thread but blocks the calling one, so it defeats the purpose.

fun getCrimes(): ArrayList = runBlocking(Dispatchers.Default) {
val result = async { retrieveCrimes() }.await()
[email protected] result as ArrayList
}

I still want to get the result but do not want to block the main thread

Will

2 months ago

Not yet. Question.
If for example I make a suspend function like this:

suspend fun retrieveCrimes(): List {
return crimesDAO.getAllCrimes() // This is the actual call to the DAO
}

How can I call it without blocking the main thread. What I tried (copied below) creates a new thread but blocks the calling one, so it defeats the purpose.

I still want to get the result but do not want to block the main thread

Development made simple

We're here to help you. If you have any questions, let us know.

Copyright 2017 - 2018 Reso Coder © All Rights Reserved