Chris Fillmore
08/25/2021, 5:27 PMclass MyComponent {
private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
fun close() {
scope.cancel()
}
}
CoroutineScope with Dispatcher + Job:
class MyComponent {
private val job = Job()
private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + job)
fun close() {
job.cancel()
}
}
The second example is used e.g. in https://kenkyee.medium.com/android-kotlin-coroutine-best-practices-bc033fed62e7
I’m grateful for any insight! Thank you!Nick Allen
08/26/2021, 4:59 PMCoroutineScope factory function will add a Job if one is not already in the CoroutineContext provided. The CoroutineScope.cancel method just calls Job.cancel.
The only benefit to creating the Job explicitly first would be that you have easier access to it if you need it for other functionality besides cancel. You could still grab it yourself, though, or even add your own helper like:
fun CoroutineScope.join() = coroutineContext[Job]?.join() ?: error("Can not join CoroutineScope with no Job")Chris Fillmore
08/26/2021, 5:00 PM