Loney Chou
07/28/2022, 3:31 PMresumes
mean for continuations? Where and when the code after suspension point run? Like if the continuation runs in an infinite loop, does it mean that resumes
will never end?efemoney
07/29/2022, 10:23 AMsuspend fun myFun() = suspendCancellableCoroutine { continuation ->
onWorkComplete { continuation.resume() }
}
// and
1 - suspend fun loop() {
2 - while(true) {
3 ~ myFun()
4 - }
5 - }
Execution “suspends” on line 3 when myFun
is invoked and the continuation.resume
resumes the suspended execution.
So in “reality” you didnt actually “leave” line 3 while myFun
was running. Execution is basically
• check condition
• enter while loop
• suspend while loop! (by entering myFun
)
• - myFun does its work
• - continuation.resume() after work is done
• resume while loop
• (repeat all over)suspend fun myFun() = suspendCancellableCoroutine { continuation ->
while(true) {
continuation.resume()
}
}
🤔 ?Nick Allen
07/31/2022, 7:33 PMWhat doesContinuation is just a callback.mean for continuations?resumes
resume
is how you invoke it.
Where and when the code after suspension point run?
resume
passes the callback to a dispatcher, the dispatcher runs the code.
Like if the continuation runs in an infinite loop, does it mean thatUsually the dispatcher letswill never end?resumes
resume
return right away and invokes the callback later in it's thread pool. If the dispatcher (like Unconfined) runs the callback directly then, resume won't return until the resumed code finishes or suspends and if neither happens then it's blocked forever.
I’m a bit curious if above is what you meant or you mean something like this instead
```suspend fun myFun() = suspendCancellableCoroutine { continuation ->
while(true) {
continuation.resume()
}
}```No, this doesn't really make any sense.
suspendCancellableCoroutine
returns with the value you resume with. So calling resume multiple times is like returning multiple times. If you tried, you'd get an exception.
Plenty of articles detail how coroutines work internally which could help. For example: https://kt.academy/article/cc-under-the-hoodefemoney
07/31/2022, 7:36 PMNick Allen
07/31/2022, 7:38 PMLoney Chou
08/01/2022, 10:51 AM