How to cancel and replace Kotlin Coroutine Call

Viewed 1567

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?

2 Answers

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)
}

You can cancel your coroutine call as follow

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