Summary

In this chapter, we covered some of the most important details of how coroutines actually work. We put ourselves in the place of the compiler and transformed a suspending function into a state machine. We also analyzed big chunks of Kotlin's code to understand how a coroutine is intercepted in order to change (or not change) its thread, as well as to understand how exceptions are propagated. Here are some things you should remember:

  • The suspending computations are transformed into state machines, and via the use of CPS they become callbacks for other suspending functions.
  • The Kotlin language itself had little changes made to it in order to support coroutines. Most of the work is done by the compiler and the coroutines library.
  • Continuations are wrapped into DispatchedContinuations at runtime. This allows the CoroutineDispatcher to intercept the coroutine, both when started and when resumed. At this point, the thread will be enforced—except for UNCONFINED.
  • If the CoroutineContext doesn't have a CoroutineExceptionHandler and the uncaught exception is not CancellationException, the framework will cancel the Job—if any—and allow platform-specific code to handle the exception.
  • In JavaScript, the platform-specific handling will simply log the exception.
  • In the JVM, it will try to find CoroutineExceptionHandlers using ServiceLoader. All the handlers found will receive a notification of the exception. After this, the JVM implementation of handleCoroutineExceptionImpl() will forward the exception to the uncaughtExceptionHandler of the current thread.
..................Content has been hidden....................

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