如何使用Kotlin协程最大程度地减少Web服务调用次数? [英] How to minimize the number of webservice calls using Kotlin coroutines?

查看:62
本文介绍了如何使用Kotlin协程最大程度地减少Web服务调用次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Android Kotlin项目中,我在协程中调用了一个Web服务(myWebservice只是一个管理Web服务调用的自定义类):

In my Android Kotlin project, I call a webservice in a coroutine (myWebservice is just a custom class that manages webservice calls):

fun searchForItems(userInput: String)
{
    CoroutineScope(Dispatchers.IO + Job()).launch {
        val listOfItems = myWebService.call(userInput)
    }
}

每次用户在EditText中键入字符时都会调用该方法,因此应用程序将调用Web服务,该服务将返回与他的请求匹配的项目列表.但我想对此进行优化.

That method is called everytime a user types a character in an EditText, so the app calls a webservice that returns a list of items matching his request. But I want to optimize that.

比方说,用户键入单词:"apple".为了最大程度地减少Web服务调用的次数,这是我要实现的目标:

Let's say that the user types the word: "apple". In order to minimise the number of webservice calls, here is what I want to achieve:

  • 当用户键入第一个字母(a)时,将调用Web服务
  • 当用户键入下一个字母时,只要没有返回第一个被调用的电话,就不会有新的网络服务调用(假设他有足够的时间键入下一个字母(pple))
  • 完成第一个网络服务调用后,将使用新的用户输入(苹果)自动完成一个新的调用

实现该目标的最佳实践是什么? 还是有更好的方法来最大程度地减少网络服务调用次数?

What would be the best practices to achieve that? Or is there a better way to minimize the number of webservice calls?

谢谢.

推荐答案

使用Kotlin协程,我像这样解决它:

Using Kotlin coroutines I solved it like this:

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毫秒后输入另一个字母,将再次调用search()函数,并使用searchJob?.cancel()函数取消先前的协程,并且不会在第一个协程中调用WebService.

When user enters first letter search() function is called, coroutine is launched and Job of this coroutine is saved to searchJob. Then delay(300) function is called to wait for another user input before calling the WebService. If user enters another letter before 300 milliseconds expire search() function will be called again and previous coroutine will be cancelled using searchJob?.cancel() function and WebService will not be called in the first coroutine.

这篇关于如何使用Kotlin协程最大程度地减少Web服务调用次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆