Hi guys, I want to know `GlobalScope` is good opti...
# coroutines
k
Hi guys, I want to know
GlobalScope
is good option when we want to configure something in the application start?
Copy code
GlobalScope.launch {
    withTimeout(60000) { // 1 minute
        // code in here
    }
}
s
It's fine as long as the code being called doesnt expect its CoroutineScope to be ever cancelled (GlobalScope can't be cancelled).
n
I don't know your use case, but if it's mandatory that your "code in here" is executed before any screen is shown / server is up, you can use
runBlocking
instead of
GlobalScope.launch
. This will block the current thread until the coroutine is finished.
k
@Nino I was changed the
runBlocking
to
GlobalScope
because it blocks the UI in launchscreen.
@streetsofboston if
GlobalScope
cannot be cancelled so how it will stop?
s
Any Job launched in the GlobalScope will just ends how it would end in any other scope. But cancelling the GlobalScope will do nothing (as opposed to non-GlobalScopes, where cancelling them will cancel all their child-Jobs).
k
okk got it now
g
But you can cancel the launched Job itself, just not scope (just because it doesn't have own Job in context)