Coroutines

Coroutines are designed to provide a way to avoid blocking a thread when we need to perform an expensive operation and replace it with a cheaper and more controllable operation: suspension of a coroutine.

Coroutines simplify asynchronous programming. The logic of the program can be expressed sequentially in a coroutine and the underlying library will figure out the asynchrony for us. The code remains as simple as if it was written for sequential execution.

To learn more about coroutines, visit: https://kotlinlang.org/docs/reference/coroutines.html.

And, as we already mentioned, coroutines are cheaper than threads.

Since coroutines are not part of the basic core package of Kotlin yet, we need to add a line to our dependencies on the build.gradle to be able to use them:

dependencies {
[...]
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5"
}

Coroutines are complex and provide many interesting features, especially for syncing the executions of asynchronous code. We are going to use them in the most basic way: to simplify the loop, make it more readable than with a Thread, and more efficient on runtime.

The code for blinking an LED using a Kotlin coroutine is as follows:

class BlinkCoroutineActivity : Activity() {

private lateinit var led: Gpio
private lateinit var job: Job

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setup()
job = launch {
while(isActive) {

loop()
}
}
}

private fun setup() {
led = RainbowHat.openLedGreen()
}

private suspend fun loop() {
led.value = !led.value
delay(1000)
}

override fun onDestroy() {
super.onDestroy()
job.cancel()
led.close()
}
}

We can see several differences. The first one is the use of the launch keyword. It basically creates a coroutine and executes the lambda on it. It returns a variable that is the job itself.

We can also see that the loop method now includes the suspend modifier. This indicates that the method can be suspended. Again, we are just scratching the surface of coroutines.

Another difference is that we use delay instead of Thread.sleep, which is a more efficient way to handle waiting times.

Finally, instead of interrupting the thread, we just cancel the job.

But those methods are related to active waiting. We can and should do better. If we think about this problem the Android way, the tool we would use is either a Handler or a Timer, so let's explore both.

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

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