8.5.1 Coroutines

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously.

If you were to run a networking request on its own, there can be many things that goes wrong. Perhaps the networking request takes a long time to complete, and the user is left waiting. Perhaps the networking request fails, but the application has no way to detect and handle the failure. This is where coroutines come into play.

Blocking vs Suspending Functions

One of the most important characteristics of coroutines is that it supports suspending functions. Normally when a networking call is made out without some sort of wrapper, it is a blocking call where it blocks all other operations on the thread unless the call is completed. This is not ideal as we don't want to leave the user hanging.

In the example below, Function A and Function B are blocking calls where Function B cannot run until Function A has been completed.

However, with coroutines, we can build suspended calls where several functions can run concurrently. In the example below, even if Function A is started first, it will suspend itself to allow Function B to run and finish before unsuspending and finishing. The great thing about coroutines is that it'll figure out the order of suspending functions to optimize the runtime for developers!

Figure 1 and 2 source

Last updated