Coroutines on Android (part II): Getting started

Sean McQuillan
May 2 · 12 min read

Other articles in this series:

Keeping track of coroutines

A leaked coroutine can waste memory, CPU, disk, or even launch a network request that’s not needed.

Cancel work with scopes

A CoroutineScope keeps track of all your coroutines, and it can cancel all of the coroutines started in it.

Starting new coroutines

scope.launch {
// This block starts a new coroutine
// "in" the scope.
//
// It can call suspend functions
fetchDocs()
}

Launch is a bridge from regular functions into coroutines.

Start in the ViewModel

Structured concurrency guarantees when a scope cancels, all of its coroutines cancel.

class MyViewModel(): ViewModel() {
fun userNeedsDocs() {
// Start a new coroutine in a ViewModel
viewModelScope.launch {
fetchDocs()
}
}
}
fun runForever() {
// start a new coroutine in the ViewModel
viewModelScope.launch {
// cancelled when the ViewModel is cleared
while(true) {
delay(1_000)
// do something every second
}
}
}

Keep track of work

Structured concurrency guarantees that when a suspend function returns, all of its work is done.

suspend fun fetchTwoDocs() {
coroutineScope {
launch { fetchDoc(1) }
async { fetchDoc(2) }
}
}

coroutineScope and supervisorScope let you safely launch coroutines from suspend functions.

Lots and lots of work

Animation showing how a coroutineScope can keep track of one thousand coroutines.

coroutineScope and supervisorScope will wait for child coroutines to complete.

Signal errors when a coroutine fails

val unrelatedScope = MainScope()// example of a lost error
suspend fun lostError() {
// async without structured concurrency
unrelatedScope.async {
throw InAsyncNoOneCanHearYou("except")
}
}

Structured concurrency guarantees that when a coroutine errors, its caller or scope is notified.

suspend fun foundError() {
coroutineScope {
async {
throw StructuredConcurrencyWill("throw")
}
}
}

Using structured concurrency

What’s next?

Android Developers

The official Android Developers publication on Medium

Thanks to Joshua Baxter and Lyla Fujiwara.

Sean McQuillan

Written by

Android Developer Advocate @Google

Android Developers

The official Android Developers publication on Medium