Easy coroutine cancelation
In this recipe, we are going to explore how to implement a coroutine that allows us to cancel its execution. We are going to create an infinite progress-bar animation running in the console in the background using a coroutine. Next, after a given delay, we are going to cancel the coroutine and test how the animation behaves.
Getting ready
The first step to start working with Kotlin Coroutines is to add a core framework dependency to the project:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.3'
The preceding code declares the kotlinx-coroutines-core
dependency in a Gradle build script, which is used in the sample project (https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook).
How to do it...
- Implement a suspend function responsible for displaying an infinite progress-bar animation in the console:
private suspend fun `show progress animation`() { val progressBarLength = 30 var currentPosition = 0 while (true) { print("\r") val progressbar...