Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelGuther/6ccdc51bf004a8a2cc605b209e890fc4 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/6ccdc51bf004a8a2cc605b209e890fc4 to your computer and use it in GitHub Desktop.
Coroutine Scope and dispatchers
Dispatchers.Default - Uses a thread pool equivalent to number of CPU cores. Should be used for CPU bound workload.
Dispatchers.IO - Uses a pool of 64 threads. Ideal for IO bound workload, where the thread is usually waiting; maybe for network request or disk read/write.
Dispatchers.Main (Android only): Uses main thread to execute the coroutines. Ideal for updating UI elements.
GlobalScope.launch(Dispatchers.IO): Launches a top-level coroutine on Dispatchers.IO. Coroutine is unbound and keeps running until finished or cancelled. Often discouraged since programmer has to maintain a reference to join() or cancel().
GlobalScope.launch: Same as above, but GlobalScope uses Dispatchers.Default if not specified. Often discouraged.
CoroutineScope(Dispatchers.IO).launch: Creates a coroutine scope which uses Dispatchers.IO unless a dispatcher is specified in the coroutine builder i.e. launch
CoroutineScope(Dispatchers.IO).launch(Dispatchers.Main): Bonus one. Uses the same coroutine scope as above (if the scope instance is same!) but overrides Dispatcher.IO with Dispatchers.Main for this coroutine.
lifecycleScope.launch(Dispatchers.IO): Launches a coroutine within the lifecycleScope provided by AndroidX. Coroutine gets cancelled as soon as lifecycle is invalidated (i.e. user navigates away from a fragment). Uses Dispatchers.IO as thread pool.
lifecycleScope.launch: Same as above, but uses Dispatchers.Main if not specified.
Explantion
Coroutine scope promotes structured concurrency, whereby you can launch multiple coroutines in the same scope and cancel the scope (which in turn cancels all the coroutines within that scope) if the need be. On the contrary, a GlobalScope coroutine is akin to a thread, where you need to keep a reference in-order to join() or cancel() it. Here's an excellent article by Roman Elizarov on Medium.
CoroutineDispatcher tells the coroutine builder (in our case launch {}) as to which pool of threads is to be used. There are a few predefined Dispatchers available.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment