article banner

Coroutines built-in support vs library

This is a chapter from the book Kotlin Coroutines. You can find it on LeanPub or Amazon.

When talking about coroutines, it's common to refer to them as a single concept. In fact, they consist 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 concurrency style known from other programming languages, but 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. This 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 and gives 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 the kotlin.coroutines package.Elements are in the 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 for direct use.
Allows nearly any concurrence style.Designed for one concrete concurrence style.

Currently, built-in support and the kotlinx.coroutines library 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's Goroutines). The current concurrency style offered by kotlinx.coroutines is elegant, convenient, and aligned with other patterns in the programming ecosystem. However, patterns and programming styles change over time. Maybe one day our community 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 promising new library might even replace the kotlinx.coroutines library. Who knows what the future will bring?

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.