Introducing Coroutines
Learn the basics of coroutines and how to implement them in Kotlin.
We'll cover the following...
Introducing coroutines
In addition to the threading model provided by Java, Kotlin also has 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 this in our Gradle configuration file—that is, build.gradle.kts
:
dependencies {...implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1")}
First, we will compare starting a new thread and a new coroutine.
Starting coroutines
We already know how to start a new thread in Kotlin. Now, let’s start a new coroutine instead.
We’ll create almost the same example we did with threads. Each coroutine will increment some counter, sleep for a while to emulate some kind of I/O, and then increment it again:
val latch = CountDownLatch(10_000)val c = AtomicInteger()val start = System.currentTimeMillis()for (i in 1..10_000) {GlobalScope.launch {c.incrementAndGet()delay(100)c.incrementAndGet()latch.countDown()}}latch.await(10, TimeUnit.SECONDS)println("Executed ${c.get() / 2} coroutines in ${System.currentTimeMillis() - start}ms")
The first way of starting a new coroutine is by using the launch()
function. Again, note that this ...