What does `resumes` mean for continuations? Where ...
# coroutines
l
What does
resumes
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?
e
A continuation instance is for a particular “suspension”. If you have:
Copy code
suspend 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)
I’m a bit curious if above is what you meant or you mean something like this instead
Copy code
suspend fun myFun() = suspendCancellableCoroutine { continuation ->
  while(true) { 
    continuation.resume() 
  }
}
🤔 ?
n
What does
resumes
mean for continuations?
Continuation is just a callback.
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 that
resumes
will never end?
Usually the dispatcher lets
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-hood
e
I know it doesnt make sense. I’m just wondering still if thats what OP meant by his question
n
Oops,I got mixed up, thought that was from the OP 😅
l
Thank you two for clearing up 😄 Now I know that `resumes`returns on suspension. That's what I don't understand at the first place.