...

/

Constructing a Coroutine Scope

Constructing a Coroutine Scope

A summary of constructing a coroutine scope and how to write code on Android.

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.

Press + to interact
interface CoroutineScope {
val coroutineContext: CoroutineContext
}

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

Press + to interact
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 ...