Context switching
One particularity of coroutines is that they can be resumed in a different context than the one they were initially started in. The CoroutineContext
, as we have seen throughout the book, is not only about the thread or pool of threads to be used. It can contain other important configurations, such as exception handling.
As we saw at the beginning of the previous section, the Continuation
interface defines that the CoroutineContext
has to be stored inside the continuation. This guarantees that during execution, it will be possible to use that context when starting or resuming the continuation.
Let's take a look at how the context is set in order to allow thread switching.
Thread switching
There is one interface and two classes that we need to get familiar with in order to understand how coroutines are executed according to the context.
ContinuationInterceptor
As we discussed earlier in the book, the CoroutineContext
behaves like a map where all the different CoroutineContext...