Search code examples
androidkotlinkotlin-coroutines

Kotlin Android Coroutine scopes - reusing scope from variable vs creating scope in function


I'm wondering what the difference is between these two approaches, my understanding is that they both work but option 1 is best practice.

I would like to know a bit more of the nitty gritty on how they work are there performance improvements or does option 1 just the ability to cancel all coroutines tied to that scope? Do both still end up using the same thread pool under the hood via Dispatchers.Main?

Option 1

private val scope = CoroutineScope(Dispatchers.Main)

fun doSomethingInCoroutine() {
    scope.launch {
        //Coroutine code
    }
}

Option 2

fun doSomethingInCoroutine() {
    CoroutineScope(Dispatchers.Main).launch {
        //Coroutine code
    }
}

I've tried both and they both work but I am looking for a deeper understanding.


Solution

  • With option 1 doSomethingInCoroutine launches all coroutines in the same scope. That allows you to simply cancel that scope if you want to cancel all of those coroutines if they are still running.

    With option 2 the scope is local to doSomethingInCoroutine. When that function ends there is no way you can cancel any coroutines that are still running.

    You should also try to minimize the use of CoroutineScope(), especially when you don't provide a parent job that can be used to cancel the scope. In that regard neither option 1 nor option 2 is recommended.

    This is especially true for Android where you should only use the provided scopes, like viewModelScope (or, in case you use Compose, rememberCoroutineScope()). These are managed by the Android SDK and cancelled when not needed anymore, allowing your coroutines to be automatically cleaned up as well in that case.