Using Coroutines on Android
Coroutines is a Kotlin library you can use to manage background tasks, such as making network calls and accessing files or databases. Kotlin Coroutines simplifies your asynchronous programming in Android by allowing you to code sequentially the tasks that will be run in a suspending function and then resume afterward. Google has updated its libraries to support Coroutines, and most third-party libraries have added support too.
You can use Coroutines in your Android project by including the latest version of org.jetbrains.kotlinx: kotlinx-coroutines-core
(the core library for Coroutines) and org.jetbrains.kotlinx: kotlinx-coroutines-android
(the library that adds support for Android’s main thread) in your version catalog file and add it to your app module’s build.gradle
file’s dependencies
block.
If you want to make a function a suspending function, add the suspend
keyword to it. Let’s say you have the following function...