Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 565
Hector Avatar asked Oct 08 '19 08:10

Hector


People also ask

Can coroutines be suspended and resumed?

Suspending functions are at the center of everything coroutines. A suspending function is simply a function that can be paused and resumed at a later time. They can execute a long running operation and wait for it to complete without blocking.

How do you stop coroutines from working?

cancelAndJoin() // cancels the job and waits for its completion println("main: Now I can quit.")

Can coroutine replace thread?

You can suspend execution and do work on other threads while using a different mechanism for scheduling and managing that work. However, this version of kotlinx. coroutines cannot change threads on its own.


1 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)
}
like image 67
Andrei Tanana Avatar answered Oct 06 '22 07:10

Andrei Tanana