One of the interesting features of Kotlin is coroutines. In Android development, the management of threads has always been a little bit challenging because there are limitations on dealing with things related to UI or the main thread. And it’s been common practice to use UI or main thread for UI-related operations and background threads for blocking operations like network calls, database operations, heavy computation tasks, etc.

If the thread management is not done properly it has a huge impact on the app’s performance, resulting in ANRs, UI freezing, crashes, etc. So it’s crucial to do things on the right thread.

Thread management or multi-threading can be achieved in many ways. But Kotlin Coroutines provide the simplest solution for handling threads. Coroutines are nothing but lightweight threads. They provide us with an easy way to do synchronous and asynchronous programming. Coroutines allow us to replace callbacks and build the main safety without blocking the main thread.

Let’s see how to do that.

Note: The _AsyncTask_ class was deprecated in Android 11. Kotlin coroutines are now the recommended solution for async code.


Usage of Suspend Functions

Let’s understand this by taking a simple example of fetching the user details from an API request or local database and displaying them to the user. If we try to fetch the details through an API call on the main thread, it throws a NetworkOnMainThreadException. If we fetch the details from the database, this operation will block the main thread from executing its operations until the data has been fetched, resulting in bad user experience.

Image for post

Photo by the author.

We can simply do this by using suspend functions in coroutines. suspendis an indication saying that the method associated with this modifier is synchronous and will not be returned immediately. The method associated with it will be suspended for a while and then return the result when available.

suspend fun loadUser(){
	 val user = api.fetchUser()
	 show(user)
	}

Let’s visualize it more clearly:

Image for post

Photo by the author.

#androiddev #programming #android #kotlin #mobile

Asynchronous Programming With Kotlin Coroutines
1.30 GEEK