https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

Chris Fillmore

08/25/2021, 5:27 PM
Hello, I’m trying to understand best practice for creating a CoroutineScope for some component I have. I don’t know what the difference is between these two approaches: CoroutineScope from Dispatcher:
Copy code
class MyComponent {
  private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
  
  fun close() {
    scope.cancel()
  }
}
CoroutineScope with Dispatcher + Job:
Copy code
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!
☝️ 3
n

Nick Allen

08/26/2021, 4:59 PM
There is no difference. The
CoroutineScope
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:
Copy code
fun CoroutineScope.join() = coroutineContext[Job]?.join() ?: error("Can not join CoroutineScope with no Job")
c

Chris Fillmore

08/26/2021, 5:00 PM
Thanks for responding! I appreciate the answer, that’s helpful
9 Views