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.

  1. Launch: if you want to start the coroutine without returning any object.

     fun main(args: Array<String>) = runBlocking {
         launch {
             // some task here
  2. 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()


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.

  1. Dispatcher Default: This dispatcher is is used by all standard builders like launch, async, etc.

  2. Dispatcher IO: This dispatcher is used when you had task to read or write data to a disk or a network

  3. Dispatcher Main: This dispatcher will run on main thread and can be used to update user interface


Scope is used to control how long your coroutine running, there are 3 type of coroutine scope on android.

  1. LifecycleScope: Scope that used on Activity or Fragment, this scope will be canceled when lifecycle destroyed.

  2. ViewModelScope: Scope that used on View Model, this scope will be canceled when view model cleared

  3. CoroutineScope: Regular scope that will be canceled when you call cancel().