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?
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.
cancelAndJoin() // cancels the job and waits for its completion println("main: Now I can quit.")
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With