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) {
...
}
}