ceving
ceving

Reputation: 23856

Kotlin suspendCoroutine

I try to understand the documentation of suspendCoroutine.

In this function both Continuation.resume and Continuation.resumeWithException can be used either synchronously in the same stack-frame where the suspension function is run or asynchronously later in the same thread or from a different thread of execution.

This sounds to me like: "resume can be used everywhere".

Is there anything left, I am not aware of?

Update for the closing gang having problems to understand anything: The documentation list three restrictions:

  1. synchronously
  2. asynchronously
  3. in other thread

The question is: why are the restrictions enumerated, if the sum of all restricitons is no restriction?

Upvotes: 1

Views: 814

Answers (1)

Sam
Sam

Reputation: 9944

Yes, you can resume a continuation from anywhere. It's an error to try and resume the same continuation more than once, though.

  • If you call resume immediately, during the call to suspendCoroutine, the coroutine does not suspend.
  • If you don't call resume immediately, that's what results in a coroutine suspension. The suspended coroutine then resumes when you later call resume from some other control flow.

The continuation you receive from suspendCoroutine is intercepted by the context's dispatcher. When you resume a suspended coroutine via an intercepted continuation, the coroutine resumes on the dispatcher, rather than running on the thread from which you resumed it.

Upvotes: 1

Related Questions