Let’s say you want to use Coroutine with code that used futur (which corresponds to several libraries such as reactor). We are going to call ‘savePost’ which returns the future ‘Call
If so, we need the conversion code as below.
How to implement it?
Any kind of synchronous future has a method to install callback. For example retrofit, there’s in queue.
But every callback having defferent futures call is a different way. Then make different name of each function, implementation and using will complicated.
Standard library in coroutine provides a function all suspendCorouine. That’s exactly the building block that were using to implement all those ways for all dfferent kinds of future.
let’s take a closer look at what’s at that is.
suspendCoroutine
Inside of it is just regular lambda that doesn’t have a suspend modifier. so it is kind of reverse separation to coroutine builder. It takes a lambda with a Continuation
parameter as an argument. The function uses this Continuation
object to suspend the current coroutine until the callback is called. Once this happens, the Continuation
object resumes the coroutine and passes the result of the callback back to the calling code.
By definition, a call to any suspend function may yield control to other coroutines within the same coroutine dispatcher. So this is exactly what happens with the function that we’ve just constructed with the help of the suspendCoroutine()
call.
The suspendCancellableCoroutine()
works similarly to the suspendCoroutine()
, with the difference being that it uses a CancellableContinuation, and the produced function will react if the coroutine it runs in is canceled.
This atually inspired by the operator that named call with current continuation in the Lisp FEM language called scheme.
reference