Continuations

So, now that we have a bare function that can resume execution in a different point, we need to find a way to indicate the label of the function. Here is where Continuation takes the spotlight. Say that we implement a continuation at the very start of our function, one that will simply redirect any invocation to the callback back at the same function.

To be able to resume, we need to have at least the label. So we'll create an implementation of CoroutineImpl, which is an abstract implementation of Continuation that already includes a label property. The only abstract function in CoroutineImpl is doResume(), so that's the only thing we need to implement at this point:

suspend fun getUserSummary(id: Int): UserSummary {
val sm = object : CoroutineImpl {
override fun doResume(data: Any?, exception: Throwable?) {
// TODO: Call getUserSummary to resume it
}
}
}

So, then, we just need to receive Continuation<Any?> as a parameter. That way, we can have doResume() forward the callback to getUserSummary(), as shown here:

suspend fun getUserSummary(id: Int, 
cont: Continuation<Any?>): UserSummary {

val sm = object : CoroutineImpl {
override fun doResume(data: Any?, exception: Throwable?) {
getUserSummary(id, this)
}
}

val state = sm as CoroutineImpl
when(state.label) {
...
}
}
Notice that we aren't receiving CoroutineImpl directly in getUserSummary(). That is because we want to invoke cont at the completion of getUserSummary(), so that the caller of it gets resumed as well; so for compatibility, it makes more sense to receive a Continuation<Any?> in case the caller didn't use CoroutineImpl.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.17