android - 如何使用 Kotlin 协程最小化 Web 服务调用的数量?
问题描述
在我的 Android Kotlin 项目中,我在协程中调用了一个 Web 服务(myWebservice
只是一个管理 Web 服务调用的自定义类):
fun searchForItems(userInput: String)
{
CoroutineScope(Dispatchers.IO + Job()).launch {
val listOfItems = myWebService.call(userInput)
}
}
每次用户在 中键入字符时都会调用该方法EditText
,因此应用程序会调用 Web 服务,该服务会返回与他的请求匹配的项目列表。但我想优化它。
假设用户输入了单词:“apple”。为了最大限度地减少 web 服务调用的数量,这是我想要实现的:
- 当用户键入第一个字母 (a) 时,将调用 Web 服务
- 当用户输入下一个字母时,只要第一个调用没有返回,就没有新的 web 服务调用(假设他有足够的时间输入下一个字母(pple))
- 当第一次 web 服务调用完成时,新的调用会自动使用新的用户输入(苹果)
实现这一目标的最佳实践是什么?或者有没有更好的方法来最小化 Web 服务调用的数量?
谢谢。
解决方案
使用 Kotlin 协程我解决了这个问题:
class SomeViewModel : ViewModel() {
private var searchJob: Job? = null
fun search(userInput: String) {
searchJob?.cancel() // cancel previous job when user enters new letter
searchJob = viewModelScope.launch {
delay(300) // add some delay before search, this function checks if coroutine is canceled, if it is canceled it won't continue execution
val listOfItems = myWebService.call(userInput)
...
}
}
}
当用户输入第一个字母search()
函数被调用时,协程被启动并且Job
这个协程被保存到searchJob
. 然后delay(300)
调用函数以在调用 WebService 之前等待另一个用户输入。如果用户在 300 毫秒之前输入另一个字母 expiresearch()
函数将被再次调用,并且先前的协程将使用searchJob?.cancel()
函数取消并且 WebService 不会在第一个协程中被调用。
推荐阅读
- hyperledger-fabric - 超级账本结构上的智能合约升级超时
- react-native - 任务 :app:compileDebugJavaWithJavac 失败
- javascript - 在反应中与 FileReader 异步
- java - 应用程序从后台重新启动主要活动,而不是恢复以前的状态
- dialogflow-es - 在 Dialogflow 上循环设置参数输出上下文
- asp.net-web-api - ASP.Net web api2 - 当 api 返回布尔值时不起作用
- sql - 从另一个表 SQL Server 更新值
- ios - 无法使用助手编辑器将表格单元 UI 连接到代码
- python-3.x - 在 R markdown 中渲染熊猫表
- c++ - g++ 是否错误地抛出 -Wnarrowing?