Halina
07/01/2025, 7:01 AMBogdan Vladoiu Lbs
07/01/2025, 7:14 AMBogdan Vladoiu Lbs
07/01/2025, 7:15 AMmarcinmoskala
07/01/2025, 8:01 AMBogdan Vladoiu Lbs
07/01/2025, 8:27 AMmarcinmoskala
07/01/2025, 8:40 AMsuspend getToken(): Token {
val token = generateToken()
applicationScope.launch { saveTokenToDb(token) }
return token
}
I completely agree with that staying on the same scope should be the most basic way of operating in coroutines. Still, as a pratcicioner, I often meet with business requirements (especially on backend) where it is requested to start a process of doing something without waiting for its completion. I also regularly meet with cases when processes should outlive coroutines that started them. Do you have any better suggestion for those cases rather than using external scope?Bogdan Vladoiu Lbs
07/01/2025, 8:41 AMmarcinmoskala
07/01/2025, 8:41 AMBogdan Vladoiu Lbs
07/01/2025, 8:45 AMmarcinmoskala
07/01/2025, 8:57 AMsuspend getToken(): Token {
val token = generateToken()
runBlocking { saveTokenToDb(token) } // NO-GO!
return token
}
Bogdan Vladoiu Lbs
07/01/2025, 8:59 AMsuspend fun getTokenBadExample(): Token {
val token = generateToken()
coroutineScope { // A new, temporary scope is created here
saveTokenToDb(token) // This call runs directly within this temporary scope.
// It's a suspend function, so the coroutineScope block
// will suspend until saveTokenToDb completes.
} // The temporary scope implicitly completes (and is effectively "thrown away")
// as soon as saveTokenToDb(token) finishes.
return token
}
this was your example. and they way you flipped it here is called sometimes, gaslighting. just like assuming people make mistakes when they use coroutines.Bogdan Vladoiu Lbs
07/01/2025, 8:59 AMmarcinmoskala
07/01/2025, 9:01 AMgetTokenBadExample
suggests that pretty clealry.marcinmoskala
07/01/2025, 9:02 AMsuspend fun getToken(): Token {
val token = generateToken()
saveTokenToDb(token)
return token
}
marcinmoskala
07/01/2025, 9:07 AMBogdan Vladoiu Lbs
07/01/2025, 9:10 AMmarcinmoskala
07/01/2025, 9:11 AMmarcinmoskala
07/01/2025, 9:12 AMmarcinmoskala
07/01/2025, 9:13 AM