首页 > 解决方案 > 如何使用 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 服务调用的数量,这是我想要实现的:

实现这一目标的最佳实践是什么?或者有没有更好的方法来最小化 Web 服务调用的数量?

谢谢。

标签: androidkotlinkotlin-coroutinesdebouncing

解决方案


使用 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 不会在第一个协程中被调用。


推荐阅读