Leave a rating/review
To put it very naively and simply, coroutines are functions which you can run in parallel.
They can also be cancelled once started unlike regular functions.
They are asynchronous by default, and can be paused and resumed at any point in time.
This concept is called suspending.
Think of it this way. If you’re cooking something, you often pause the process, and resume it later on.
You start stirring the soup for example, and then you can go slice something else.
Then after a while, you can go back to stirring the soup.
This is the process of suspending and resuming.
You can also cancel the process of preparing the soup. It won’t affect cooking the cake for example.
Coroutines require two things to work.
A CoroutineScope and a Coroutine builder.
The CoroutineScope is a way to attach the coroutine to some form of a lifecycle.
If you cancel the scope it will cancel all coroutines within it.
If you didn’t attach coroutines to anything, you could easily create memory leaks, or coroutines which never end.
By using a CoroutineScope, you tell how long the coroutine can live.
For example, if you scope a coroutine to an Activity, when the activity dies, the coroutine will be cancelled.
And to actually start Coroutines, you use special functions called coroutine builders.
The suspending function has to start from another suspending function, or a coroutine builder. To start a very first coroutine you need to use a builder.
There are three built-in coroutine builders: launch, async and runBlocking. Each of them has a different purpose and use cases.
The launch is most common one. It starts a coroutine in the background. It doesn’t return the result of the coroutine.
The async builder also starts a coroutine in the background, but it returns a wrapper for the result.
Those two builders are the extension functions on the CoroutineScope.
The runBlocking as the name suggests, blocks the current thread, until the coroutine finishes. It’s rarely useful in Android projects.
But it’s very convenient for non-Android, console applications and quick examples. It does not require a CoroutineScope.
The coroutine dispatchers are a way to tell the coroutine where to run.
If you touch the UI you have to use the Main dispatcher.
For heavy computations in the background you should use the Default dispatcher. It uses a thread pool having a size depending on the number of CPU cores.
For network or other blocking calls you should use the IO dispatcher. It also uses a thread pool, but with a larger size.
Oh well, that’s quite a lot to process.
So let’s get started and prepare for future concepts! :]