Multi-threading approach in Android is used to handle tasks on separate thread (or threads) without blocking the Main UI thread. Couroutines provides much better alternative to common solutions, such as Asyntask (currently deprecated), Thread Pool Executor and Rx Java. Coroutines are considered light-weight threads that do not block the main thread, while running code concurrently. More strictly, they are light-weight but not threads, and are blocks of code used by one or more non-blocking threads.
Some of the main features of Coroutines include:
- Coroutines are not bound to a specific thread and can suspend code execution in one and resume in another.
- Multiple coroutines can run on a single thread, with each having its own lifecycle.
- Many coroutines can run on a single thread due to support for suspension, which doesn't block the thread where coroutine runs. Suspension functions allow to start, pause and resume execution of a coroutine, within coroutine context.
- All coroutines must run inside a Coroutine Scope, which defines the coroutines lifecycle throughout their execution. Cancelling a scope, destroys all coroutines within it too. There are three kind of scopes used for Coroutines: Global Scope (coroutine maxium lives as long as application), LifeCycle Scope (coroutine maximum live with the life of Activity) and ViewModel Scope (coroutine will live maximum with ViewModel's life).
- A coroutine can be executed using various dispatchers, which decide which thread to use, switch over to or from etc. It is an optional feature, but helps precise determination which thread or thread pool coroutine runs on.
- To create a new coroutine, one of the available builder functions: runBlocking (blocks underlying thread), launch (result returned), or async (return result), can be used.