Continuations

It all starts with continuations, which can be considered the building blocks of suspending computations—after all, they are even in the name of the paradigm. The reason continuations are so important is that they are what allows a coroutine to be resumed. To make this clearer, here is the definition of the Continuation interface:

public interface Continuation<in T> {
public val context: CoroutineContext
public fun resume(value: T)
public fun resumeWithException(exception: Throwable)
}

This interface is rather simple. Let's look at a quick overview of what it defines:

  • The CoroutineContext that is to be used with this Continuation.
  • A resume() function that takes a value T as a parameter. This value is the result of the operation that caused the suspension—so, if the function was suspended to call a function that returns an Int, value will be that integer.
  • A resumeWithException() function that allows for propagation of an exception.

So, a continuation is pretty much an extended callback, one that also contains information about the context in which it should be called. As we will see later in the chapter, this context is an important part of the design, because it's what allows for each continuation to be executed in a specific thread or pool of threads—or with different configurations like exception handlers—but still remain sequential.

..................Content has been hidden....................

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