Using Coroutines on Android
Coroutines were added in Kotlin 1.3 to manage background tasks such as making network calls and accessing files or databases. Kotlin coroutines are Google’s official recommendation for asynchronous programming on Android. Their Jetpack libraries, such as LifeCycle, WorkManager, and Room, now include support for coroutines.
With coroutines, you can write your code in a sequential way. The long-running task can be made into a suspending function, which, when called, can pause the thread without blocking it. When the suspending function is done, the current thread will resume execution. This will make your code easier to read and debug.
To mark a function as a suspending function, you can add the suspend
keyword to it; for example, if you have a function that calls the getMovies
function, which fetches movies
from your endpoint and then displays it:
val movies = getMovies() displayMovies(movies)
You can make the getMovies()
function a suspending...