Coroutines

In addition to the threading model provided by Java, Kotlin also introduces a coroutines model. Coroutines might be considered lightweight threads, and we’ll see what advantages they provide over an existing model of threads shortly.

The first thing you need to know is that coroutines are not part of the language. They are simply another library provided by JetBrains. For that reason, if we want to use them, we need to specify so in our Gradle configuration file, build.gradle:

dependencies {
...
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.21"
...
}

As of Kotlin 1.2, coroutines are still considered experimental. This doesn't mean that they don't work well, though, as some might think. It only means that some parts of the API may still change in the next versions.

What could change? For example, in 0.18, an Actor, which we'll discuss later in this chapter, exposed a channel member. In 0.21, this member was made private and a method was added instead. So instead of calling actor.channel.send(), you would call actor.send().

It's fine if you're not aware what actor or channel mean at this point. We'll cover those terms in the following sections shortly.

For that reason, after you add this dependency and start using them, you may get warnings during compilation or in your IDE:

The feature "coroutines" is experimental

You can hide those warnings with the following Gradle configuration:

kotlin {
experimental {
coroutines 'enable'
}
}

Now, let's get started with coroutines.

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

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