I have the following code: ``` launch { val c...
# coroutines
a
I have the following code:
Copy code
launch {
    val cookie = web.loadLogin { refresh(it != 100) }
    L.d { "Login found" }
    FbCookie.save(cookie.id)
    web.fadeOut(onFinish = {
        profile.fadeIn()
        this@LoginActivity.launch { loadInfo(cookie) }
    })
}
This is inside an android activity, which implements coroutine scope on the main dispatcher. It took me a while to debug, buy if the second
launch
was not from the activity scope, but rather a child of the parent
launch
, it would never actually run. Fade out is a normal method with a callback, and loadInfo is a suspended function using
withContext(Dispatchers.Main)
. Why is this the case?
g
Why do you need second launch? why not just
loadInfo(cookie)
)
Not sure why it’s not “actually run”, are you sure that you do not block thread in loadInfo?
g
offtopic, interesting take on
L.d
🙂
a
The extra launch isn’t necessary, and was just because fadeOut takes in a non suspended block. I ended up converting it to a suspended method so that no extra launch was needed. The loadInfo is non blocking, and actually never gets launched to begin with (I added a logger on the first line). That’s what I was wondering about.
d
At the time of second launch, the scope from the first launch is completed, so I assume that's why it doesn't work. You should make
fadeOut()
suspend and remove the callback, inlining it after the call.
Ah, you've already done that.
a
Is that how it’s supposed to work though? That makes it sound like it isn’t possible to have nested launches at all if the parent can finish without worrying about the children
d
It depends on the implementation of fadeOut, specifically on which thread it invokes the callback.
I don't know for sure if a coroutine will start if its parent is not alive
But it probably shouldn't
a
Fade out is not a suspension function. It just runs a view animation on the main thread and uses the callback from the animator. I guess since it’s not blocking, you mean that the launch function has fully ended, and so the next launch won’t run once the callback is called?
d
Yeah if it's not blocking, I think that's correct.
👍 1