Coroutine cancellation in Android (API call cancellation)

Mohammad Fayaz
2 min readDec 25, 2022

Hello everyone, hope you are all doing good and safe wherever you are.

This article is about cancelling coroutine’s, also one best example is cancelling an ongoing API call.

So, why do we even need to cancel the coroutines?

Let’s consider a simple use-case where you have to update the search results or auto-populate based on user’s input (just like a Google search bar) where you might be using a de-bouncer technique to make API call and fetch data from the API.

If you leave the coroutine as it is without cancellation and if there is a worst case that API responds a bit late to that query or say like call1 and call2 are sent, response of call2 came first and then came call1, now the user will see response of call2 populated first and then instantly or after sometime (based on API response time) the results are replaced by the call1 which is not an ideal thing that should happen.

How do we cancel the API calls?

This is not a trivial task to do, we just have to store the instance of the coroutine in a variable and cancel it whenever we need to do it. The following code snippet will help.

var job: Job? = null

fun makeApiCall() {
if (job?.isActive == true) {
job?.cancel()
}
job = viewModelScope.launch {
// ... your API call
}
}

Here’s a video demo for API call with Coroutine Cancellation and API call without Coroutine Cancellation

Here’s link for GitHub repository , if you need to run the sample app and play around.

Thanks for reading. Follow me on GitHub, Medium

--

--