notes on Kotlin Coroutine

Jeffchan
Feb 6, 2021
  • think Coroutine as Callbacks hook rather than thread
  • runBlocking on main (UI) thread will permanently block UI, and never wake up again
  • runBlocking block the current thread until all inner code is done
  • runBlocking confines execution to a single thread, which make inner code run sequentially, use launch or make function withContext with Dispatcher.IO or Dispatcher.Default to start a new thread to achieve concurrency
  • use of GlobalScope.launch create global coroutine, which makes the coroutine lose its coroutine context (i.e. it no longer belongs to activity but application) (reference from https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc), use CoroutineScope(Dispatchers.Main).launch or MainScrope().lanuch instead
  • Dispatcher.Main will add the code to the last of the event queue (i.e. run at last), use Dispatcher.Main.immediate
  • to be continued..

--

--