If i want to call my `search` function after user ...
# coroutines
k
If i want to call my
search
function after user finish typing (by being idle for >=400ms). is this the correct way to do this with coroutines?
Copy code
fun onKeywordChanged(keyword: String) {
  keywordJob.cancel()
  keywordJob = launch {
    delay(400)
    if (!isActive) return@launch
    search(keyword)
  }
}
👍🏼 1
g
Probably can be rewritten in a much more efficient way without creating additional coroutine on each tick
👍 1
a
This looks like to me a good usecase for using csp channels and implement a debouncer on top of them
👍 1
g
Yes, writing debounce operator on top of channel of events looks as most obvious solution, but even if you don’t want to use channels you still can write much more optimal version of this code
👍 2
k
Sorry I'm a coroutines-noob. 🙂 would you share a little snippet to help me understand your point correctly?
d
as an aside, the
if (!isActive)
isn't necessary because delay() will resume with an exception if the coroutine is cancelled anyway
you can probably use
withTimeout
or the
onTimeout
clause with select to do something a bit nicer. E.g.
withTimeout(400) { keywordChannel.receive() }
the logic is a bit more complex because you need to receive the first keystroke too but yeah..