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)
}
}
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.
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:
- when the user types the first letter (a), the webservice is called
- when the user types the next letters, there is no new webservice call as long as the first called hasn't returned (let's assume that he has enough time to type the next letters (pple))
- when the first webservice call is done, a new call is done automatically with the new user input (apple)
What would be the best practices to achieve that? Or is there a better way to minimize the number of webservice calls?
Thanks.