Co means cooperation and Routines means functions. It means that when functions cooperate with each other, we call it as Coroutines

  1. coroutines are lightweight threads.

By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later.

  1. Coroutines allows execution to be paused and resumed at later in program.
  2. using coroutines we can achieve Structured concurrency.
  3. Low chances for memory leak.

A Job can be used to wait for the coroutine to do some work or it can be used to cancel it.

Structured concurrency

It help us to keep track of all work running in coroutines. if main scope gets cancel all the coroutines that are present in it get canceled.

it allows us to cancel any child coroutines , only that coroutines get cancelled other coroutines will complete their execution.

if any child throws any exception then other child coroutines get cancelled and exception will occur. to handle this exception we can use try catch block to handle that exception or we can also use CoroutineExceptionHandler to handle that exception.

Note- if we use try catch block to handle exception only that particular child get cancel other get completed, (Explain then why we use CoroutineExceptionHandler )

if we use CoroutineExceptionHandler then all child get canceled.