Hector
Hector

Reputation: 5428

How to cancel and replace Kotlin Coroutine Call

I am experimenting with Kotlin Coroutines in my current Android application.

I have a use case where a user can search for text using a remote RestFul API.

What I would like to achieve is as follows:-

1). The use types "ABC" and I start my Remote API within this search string

viewModelScope.launch {
  repository.searchAPI(searchString)
}

2). The user now types more so that my search string is now "ABCXYZ"

I now wish to cancel the initial search of "ABC" and replace it with a the new search string of "ABCXYZ"

I thought I could use this code...

viewModelScope.launch {

  if (isActive) {
    this.coroutineContext.cancelChildren()
  }

  repository.searchAPI(searchString)
}

However this cancels the entire process

How can I achieve the desired result of replacing a currently executing search with the most recent search string?

Upvotes: 9

Views: 2652

Answers (2)

Shivam Sharma
Shivam Sharma

Reputation: 96

You can cancel your coroutine call as follow

 val job =viewModelScope.launch {
      repository.searchAPI(searchString)
    }
job.cancel() // cancels the job

Upvotes: 0

Andrei Tanana
Andrei Tanana

Reputation: 8442

You can store your search job in the view model's field and cancel it on the new search. It will be something like this:

var searchJob: Job? = null
...
searchJob?.cancel()
searchJob = viewModelScope.launch {
  repository.searchAPI(searchString)
}

Upvotes: 9

Related Questions