Coroutines built-in support vs library

This is a chapter from the book Kotlin Coroutines. You can find Early Access on LeanPub.

When talking about coroutines, it's common to refer to them as a single concept. They're instead composed of two components: built-in support provided by the Kotlin language (compiler support and elements in the Kotlin standard library), and the Kotlin Coroutines library (named kotlinx.coroutines). Sometimes they are treated as the same entity, but they are very different from each other.

Built-in language support is designed to be minimalistic and give as much freedom as possible. It can be used to reproduce practically any concurrence style known from other programming languages, but at the same time, it is not convenient to use it directly. Most of its elements, such as suspendCoroutine or Continuation, are supposed to be used by library creators, rather than by application developers.

On the other hand, we have the kotlinx.coroutines library. It is a separate dependency that needs to be added to the project. It's built on top of the built-in language support. It is way easier to use, giving developers a concrete concurrence style.

Built-in supportkotlinx.coroutines library
Compiler support and elements in the Kotlin standard library.Separate dependency needs to be added to the project.
Elements are in kotlin.coroutines package.Elements are in kotlinx.coroutines package.
Minimalistic, provides a few basic elements (like Continuation or suspendCoroutine) and the suspend keyword.Provides many elements (like launch, async, Deferred).
Hard to use directly.Designed to use directly.
Allows nearly any concurrence style.Designed for one, concrete concurrence style.

Currently, those two are nearly always used together, but that's not a requirement. Many computer science papers1 show the universality of the suspension concept. It was also shown by the team working on the Kotlin Coroutines library. When looking for the best concurrency style, they used built-in Kotlin support to reproduce the concurrency styles from many other languages (like Go with its Goroutines). The current concurrency style offered by kotlinx.coroutines is elegant, convenient, and aligned with other patterns in the programming ecosystem. Although patterns and programming styles change over time. Maybe one day, our society will come up with a better concurrency style. If so, someone will most likely be able to implement it by using built-in Kotlin support and ship it as a separate library. This new promising library might even replace the kotlinx.coroutines library. Who knows what the future will bring us.

1:

For example Revisiting coroutines (2009) by Ana Lúcia De Moura and Roberto Ierusalimschy and Continuations and coroutines (1984) by Christopher T. Haynes, Daniel P. Friedman, and Mitchell Wand.