Coroutine

Coroutine

Coroutine is not a new concept, it had always been there with different language like C#, Ruby and etc.

And now, we have coroutine library implemented in Kotlin :D

What it meant to developer

Coroutine changes the way developer write programs in a nice way, under the hood they still use thread, but u dont have to spell it out. It provide a simpler Api interface

With coroutine, we can have multiple coroutine running on the same thread, not bounded by the limit of the thread we can have as thread are pretty expensive so we can run more coroutine with less resources.

It provide a really near Linear code reading experieces to user, for example:

  1. First you are going to do this on IO thread
  2. then u want to do this on ui thread
  3. then u want to do this on IO thread again
  4. at last, u want the result display on the UI thread

Several Coroutine Keyword that we should know

  • Dispatcher
  • Scope
  • Suspend

Dispatcher

  • MainDistaptcher Main Looper
  • Default Dispatcher for CPU fixed to size to the number of core
  • IO Dispatcher basically 64 thread

Scope

  • It behave like lifecycle
  • Scope is not related to thread
  • Solve problem that Android Dev faced a lot like configuration changes, rotate, lifecycle etc
  • If the scope is not valid anymore, it will cancel itself automatically
  • No more work leaks unless you are using a scope that is incorrect, for example running Global Scope on Activity, …
  • Global Scope is totally fine if you know where to use it, for example Application
  • All of the scope have a dispatcher : GlobalScope.launch
  • lifecycleScope, viewModelScope, ...

Suspend

  • In Kotlin, we have the suspend keyword to decorate function with, it give us whole bunch of promises, for example, when u make a suspend function that perform network request, by the time that suspend return, it would have completed the job
  • In other lagunage they use async await
  • Suspend wrap your function into class and it implement a state machine for you
  • With this state machine, everytime you invoke a suspend function, this suspend function can be paused at any point of time, and later point can resume with switch statement
  • Raise developer awareness so that dev know that this function is running on certain thread, without this keyword, dev may mistakenly call the function on MainThread and blocking it.
  • Details: Kotlin Compiler will compile this suspend marked function into Continuation Passing Style (CPS) for coroutine to use

Original Code

Compiled bytecode : Continuation Passing Style

Flowable

  • Included in coroutine library to provide functionality like RxJava
  • stream producer like RxJava, listening only when u need it
  • example: Location listener

Switch thread in coroutine

  • inside the same coroutine u can switch
  • withContext(Dispatcher.IO) craete a coroutine and join the current coroutine
  • Suspend and resume, core thing of coroutine,
  • A coroutine can suspend itself, mean it is not doing anywork, kinda waiting around for the result then resume with the result
  • main thread coroutine get suspend itself when the network request start to call on other thread, later when the result is ready, it will resume, state machine

Some Comparison

RxJava vs Coroutine

RxJava actually is a very powerful streaming library and actually provide far more function than just switching thread, it can act as stream producer, emiting event and etc

while Coroutine is more focus on thread side, to provide stream producer feature like RxJava, we can use Flowable to achieve that which is also a part of Coroutine implementation in Koltin.

Cancelling:

  • In RxJava, we need to composite subscription and manual cancel when needed to avoid exception & leaks
  • In Coroutine, we just need to pick the scope and it will do the magic

Performance:

  • Pretty similar

WorkManager vs Coroutine

Workmanager designed to solve deferable work, fundamental different with coroutine

Dispatcher vs Scope

  • Dispatcher -> the main thing coroutine is running on, maybe thread pool
  • Scope -> just a lifecyle, ability to cancel

Code Style : Thread VS RxJava VS Coroutine

  • RxJava - Chain Style
  • Coroutine - Linear Style
  • Thread - Callback Style

Read Up

  1. https://www.infoq.com/articles/kotlin-coroutines-bottom-up/
  2. https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md
  3. https://kotlinlang.org/docs/coroutines-guide.html
  4. https://developer.android.com/kotlin/coroutines
  5. http://androidbackstage.blogspot.com/2019/07/episode-117-kotlin-coroutines.html
  6. https://en.wikipedia.org/wiki/Coroutine

Comments