https://kotlinlang.org logo
Title
k

KotlinLeaner

05/10/2023, 10:00 AM
Hi guys, I want to know
GlobalScope
is good option when we want to configure something in the application start?
GlobalScope.launch {
    withTimeout(60000) { // 1 minute
        // code in here
    }
}
s

streetsofboston

05/10/2023, 12:21 PM
It's fine as long as the code being called doesnt expect its CoroutineScope to be ever cancelled (GlobalScope can't be cancelled).
n

Nino

05/10/2023, 1:16 PM
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

KotlinLeaner

05/10/2023, 1:26 PM
@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

streetsofboston

05/10/2023, 1:29 PM
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

KotlinLeaner

05/10/2023, 1:30 PM
okk got it now
g

gildor

05/13/2023, 2:54 PM
But you can cancel the launched Job itself, just not scope (just because it doesn't have own Job in context)