public CoroutineScope
Defines a scope for new coroutines. Every coroutine builder
is an extension on interface CoroutineScope
and inherits its CoroutineScope.getCoroutineContext
to automatically propagate both context elements and cancellation.
Every coroutine builder (like BuildersKt.launch
, BuildersKt.async
, etc)
and every scoping function (like CoroutineScopeKt.coroutineScope
, BuildersKt.withContext
, etc) provides its own scope
with its own interface Job
instance into the inner block of code it runs.
By convention, they all wait for all the coroutines inside
their block to complete before completing themselves, thus enforcing the
discipline of structured concurrency.
interface CoroutineScope
should be implemented on entities with well-defined lifecycle that are responsible
for launching children coroutines. Example of such entity on Android is Activity.
Usage of this interface may look like this:
class MyActivity : AppCompatActivity(), CoroutineScope {
lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
}
override fun onDestroy() {
super.onDestroy()
job.cancel() // Cancel job on activity destroy. After destroy all children jobs will be cancelled automatically
}
/*
* Note how coroutine builders are scoped: if activity is destroyed or any of the launched coroutines
* in this method throws an exception, then all nested coroutines are cancelled.
*/
fun loadDataFromUI() = launch { // <- extension on current activity, launched in the main thread
val ioData = async(Dispatchers.IO) { // <- extension on launch scope, launched in IO dispatcher
// blocking I/O operation
}
// do something else concurrently with I/O
val data = ioData.await() // wait for result of I/O
draw(data) // can draw in the main thread
}
}
Modifier and Type | Method and Description |
---|---|
NonExistentClass |
getCoroutineContext()
Context of this scope.
|