Get to Know Kotlin Coroutine
If you want to create an asynchronous or non-blocking task on kotlin you should consider using coroutines, according to the official documentation, coroutine is an instance of a suspendable computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular thread. It may suspend its execution in one thread and resume in another one. Let's start to learn about coroutine basics!
Starting Coroutine
There are two options to start coroutine which is launch and async, you can choose between this two options depends on your cases.
Launch: if you want to start the coroutine without returning any object.
fun main(args: Array<String>) = runBlocking { launch { // some task here } }
Async: If you want to start the coroutine and waiting for returning object as a deferred.
fun main(args: Array<String>) = runBlocking { val deferred = async { TaskWithReturnObject() } val result = deferred.await() println(result) }
Dispatchers
After we know how to start coroutine, next we need to know about dispatcher. Dispatcher let us decide where our coroutine process run, there are 3 type of dispatchers.
Dispatcher Default: This dispatcher is is used by all standard builders like launch, async, etc.
Dispatcher IO: This dispatcher is used when you had task to read or write data to a disk or a network
Dispatcher Main: This dispatcher will run on main thread and can be used to update user interface
Scope
Scope is used to control how long your coroutine running, there are 3 type of coroutine scope on android.
LifecycleScope: Scope that used on Activity or Fragment, this scope will be canceled when lifecycle destroyed.
ViewModelScope: Scope that used on View Model, this scope will be canceled when view model cleared
CoroutineScope: Regular scope that will be canceled when you call
cancel()
.
Sources:
https://kotlinlang.org/docs/coroutines-overview.html#documentation