Junior — Middle
What main methods are available in the CoroutineScope interface for managing coroutines?
sobes.tech AI
Answer from AI
The CoroutineScope interface in Kotlin provides a coroutine context and allows launching coroutines within that context. The main methods for managing coroutines are:
launch { ... }— starts a new coroutine without a return result (Job).async { ... }— starts a coroutine that returns a result asDeferred, allowing the value to be obtained later.
Example usage:
class MyScope : CoroutineScope {
override val coroutineContext = Job() + Dispatchers.Default
}
val scope = MyScope()
scope.launch {
// performs an asynchronous task
}
val deferred = scope.async {
// computation with a result
42
}
runBlocking {
println(deferred.await()) // outputs 42
}
Additionally, CoroutineScope inherits coroutineContext, which can be used to manage the lifecycle of coroutines (for example, cancellation via Job).