Search⌘ K
AI Features

Constructing a Coroutine Scope

Explore how to create and manage CoroutineScope objects in Kotlin for both Android and backend applications. Understand the use of Dispatchers, SupervisorJob for child coroutine independence, and CoroutineExceptionHandler to handle uncaught exceptions. Learn practical approaches to scope cancellation and lifecycle management in ViewModels or presenters.

In previous lessons, we’ve learned about the tools needed to construct a proper scope. It’s time to summarize this knowledge and see how we can use it. We’ll look at two common examples: one for Android, and one for back-end development.

CoroutineScope factory function

The CoroutineScope interface has a single property, coroutineContext.

Kotlin 1.5
interface CoroutineScope {
val coroutineContext: CoroutineContext
}

Therefore, we can make a class implement this interface and directly call coroutine builders in it.

Kotlin 1.5
class SomeClass : CoroutineScope {
override val coroutineContext: CoroutineContext = Job()
fun onStart() {
launch {
// ...
}
}
}

However, this approach is not very popular. On the one hand, it’s convenient; on the other, it’s problematic that in such a class, we can directly call other CoroutineScope methods like cancel or ensureActive. Even accidentally, someone might cancel the whole scope, and coroutines won’t start anymore. Instead, we generally prefer to hold a coroutine scope as an object in a property and use it to call coroutine ...