19

When launching coroutines from Activities, Fragments or Android Architecture Components ViewModels, it makes total sense to use a coroutine scope that is bound to the lifecycle of that view component in order to avoid leaks and free resources by e.g. canceling the network request when the user leaves the screen.

But there are other situations, where you don't want to cancel a coroutine even when the user leaves the screen like when you are performing a network request for analytics or writing into a database. Is it OK to launch coroutines with GlobalScope in such situations? The objects where these coroutines are launched are mostly Singletons, so they live for the lifetime of the application anyway, so there is no danger of leaks, right?

The Kotlin docs are pretty clear on GlobalScope:

Application code usually should use an application-defined CoroutineScope. Using async or launch on the instance of GlobalScope is highly discouraged.

Is it OK to use GlobalScope in these situations? If not, how should my application-defined CoroutineScope look like?

Lukas Lechner
  • 7,881
  • 7
  • 40
  • 53

2 Answers2

18

If you have an asynchronous worker whose lifecycles is truly global (they only die/end when your process dies), using GlobalScope or a similar life-long scope, is fine.

Say, you have an Activity that makes a request, but the actual network-request needs to continue even if the Activity goes away, because you'd like to cache it when the network finally returns a response.

You'll add a CoroutineScope to your Activity/Fragment, or better to your ViewModel and have your code that finally puts stuff on the screen run in that scope. When the Activity/Fragment/ViewModel dies, the scope is canceled and nothing will be attempted to show something on a screen that no longer exists.

However, your Fragment/Activity/ViewModel may talk to a data-source/repository that has a lifecycle that only ends when the process dies. You can switch to a GlobalScope in there so that your network-responses get cached, even when no Activity/Fragment/ViewModel is alive to show the result on the screen.

class MyViewModel(context: CoroutineContext, repo: MyRepository) : ViewModel() {
    private val scope = CoroutineScope(context + SuperviserJob())

    override fun onCleared() { scope.cancel() }

    fun getDataFromNetwork() {
        scope.launch {
            myLiveData.value = repo.getDataFromNetwork()
        }
    }

}

// Singleton class
class MyRepositoryImpl(context: CoroutineContext) : MyRepository {
    private val scope = CoroutineScope(context + SupervisorJob())

    override suspend fun getDataFromNetwork() : String {
        return scope.async { // switch scopes
            val data = ... fetch data ...
            saveInCache(data)
        }.await()
    }
}

When your ViewModel ends (onCleared is called), the MyRepositoryImpl's getDataFromNetwork still keeps running and will call saveInCache if all goes right. However, the value returned won't be assigned to myLiveData.value because the coroutine of your ViewModel's scope was cancelled.

jpmcosta
  • 1,752
  • 15
  • 24
Streets Of Boston
  • 12,576
  • 2
  • 25
  • 28
  • 1
    Thank you for your answer! I have two questions: 1. Is there a reason why you use .async & .await in your `getDataFromNetwork()` function? Would it be the same as using `withContext(context)` ? 2. What kind of CoroutineContext do you pass to the constructor of `MyRepositoryImpl` ? – Lukas Lechner Jun 18 '19 at 07:48
  • 1
    Using `withContext` just switches **context**, not the **scope**. You use this mostly for switching dispatchers and such. For the `context` param to `MyRepositoryImpl`; you can pass a `TestCoroutineDispatcher` for example to be able to easily test your code. – Streets Of Boston Jun 18 '19 at 14:00
1

Given that you're already trying to attach it to application's lifecycle, I'd suggest either passing the scope to your singleton or implementing a coroutinescope by it. Unfortunately, running coroutines on GlobalScope still might end in leaks. See this great article by Roman Elizarov for more info: https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc

r2rek
  • 2,083
  • 13
  • 16