Blog top image

Coroutines


  • Light weight thread 
  • Coroutines can run parallel and can communicate with each other
  • Coroutines consume less memory, performance is way better than threads  


Why we us Coroutines?

  • Async work
  • For multi threading 


How we do this?

  • Use suspended on method and
  • use coroutines to listen the result


What is Coroutine builder?

Coroutine builder are simple function that create coroutine and act as a bridge between real world and the suspended world. They are called on scope. There are three types of scopes

  • lunch: lunch coroutine and forget
  • async: Return a deferred object
  • runBlocking: Run as Main thread


Coroutine scope and dispatchers

The scope object of a Coroutine dictates how long the coroutine should live and wait for results. There are four predefine scopes 

  • Global
  • lifecycle
  • rememberCoroutine
  • viewModel

We can also define custom scopes by passing a job and a Dispatcher


What is a job?

A job can be used as a handle to coroutine where we can track the wait time and cancel it. 


What is Dispatcher?

It is used to specify which thread a coroutine uses for its execution. One can specify the dispatcher to the builder.


Dispatcher types

  • Main - UI
  • Default - CPD
  • IO - Networking or file access