Simple Example of Coroutine in Android Kotlin
In this tutorial we will learn the basics of coroutine in android with a very simple example without discuss the advanced constructs.
What is coroutine in Kotlin?
In simple words a coroutine is a lightweight thread. It is used to manage the long running tasks (which can cause app to become unresponsive) without blocking the main thread. Coroutine is a solution of asynchronous programming in Kotlin language. It is the new way of writing asynchronous code. Async code is a code that can run parallel to others.
Suspending Functions
Coroutine has the ability to calling the suspended functions on main thread. delay() and HttpClient.post() are the suspended functions in Kotlin. Delay() function is used to delay some execution of task. And HttpClient.post() method is used to make an http call over the internet to post some data. This task takes some time to make a an API call. So we have to wait for the response, and perform next action after we get response from API. To perform such tasks in Kotlin we use Coroutines.
Example
Here we will see a very simple example of Coroutine.
Add these dependencies in build.gradle file
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
MainActivity.kt
package com.example.coroutienpractice
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.coroutienpractice.databinding.ActivityMainBinding
import kotlinx.coroutines.*
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
CoroutineScope(Dispatchers.IO).launch {
makeApiCalls()
}
}
private suspend fun makeApiCalls() {
val result1 = fetchDataFromFirstApi()
println("Result $result1")
val result2 = fetchDataFromSecondApi()
println("Result $result2")
}
private suspend fun fetchDataFromFirstApi(): String {
delay(1000)
return "Result 1"
}
private suspend fun fetchDataFromSecondApi(): String {
delay(2000)
return "Result 2"
}
}
This is a very simple example of Coroutine. Hopefully you will understand it easily.
Let’s discuss the above code in detail
Here you can see that we have created suspend functions. A suspend function is a function that is starts with a suspend keyword. Suspended function suspends the execution of coroutine for some time, wait for result and after result it resumes the execution. Each suspended function can be called only from other suspended function.
In the above example we assume that we have to fetch data from two APIs, one after another. First we will fetch data from one API, after fetching the result from one API we will call the second API.
There are three suspended functions
fetchDataFromFirstApi()
This function is for calling first API. This method returns the response in 1 second.
fetchDataFromSecondApi()
This function is for calling Second API. This method returns the response in 2 seconds.
makeApiCalls()
This function is for calling both APIs one after the other. So the total time of execution will be the 3 seconds.
As you can see that each suspend function is called in other suspended function. And the base suspend function is called in coroutineScope .
Conclusion
In this tutorial we learned the basics of Coroutine in Kotlin. Coroutine is a vast topic, but here we discussed it with a very simple example to keep it short without discussing the advance constructs of Coroutine. Hope you understand this. Thank you for reading.