我正在我当前的 Android 应用程序中试验 Kotlin 协程。
我有一个用户可以使用远程 RestFul API 搜索文本的用例。
我想达到的效果如下:-
1).使用类型“ABC”,我在此搜索字符串中启动我的远程 API
viewModelScope.launch {
repository.searchAPI(searchString)
}
2).用户现在键入更多内容,因此我的搜索字符串现在是“ABCXYZ”
我现在希望取消对“ABC”的初始搜索并将其替换为新的搜索字符串“ABCXYZ”
我以为我可以使用这段代码...
viewModelScope.launch {
if (isActive) {
this.coroutineContext.cancelChildren()
}
repository.searchAPI(searchString)
}
然而这取消了整个过程
如何将当前正在执行的搜索替换为最新的搜索字符串,从而获得预期的结果?
最佳答案
您可以将搜索作业存储在 View 模型的字段中,并在新搜索时取消它。它将是这样的:
var searchJob: Job? = null
...
searchJob?.cancel()
searchJob = viewModelScope.launch {
repository.searchAPI(searchString)
}
关于android - 如何取消和替换 Kotlin Coroutine Call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282355/