Skip to content

Instantly share code, notes, and snippets.

@k-kagurazaka
Created December 1, 2017 14:18
Show Gist options
  • Select an option

  • Save k-kagurazaka/54441d6d5dfdb5668fd884008cd480a2 to your computer and use it in GitHub Desktop.

Select an option

Save k-kagurazaka/54441d6d5dfdb5668fd884008cd480a2 to your computer and use it in GitHub Desktop.
RxJava debounce like operator implementation for kotlin coroutine
launch(UI) {
editText.onTextChanged()
.debounce(1, TimeUnit.SECONDS)
.consumeEach {
Log.d("DebounceTest", "value: $it")
}
}
}
fun EditText.onTextChanged(): ReceiveChannel<String> =
Channel<String>(capacity = Channel.UNLIMITED).also { channel ->
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
editable?.toString().orEmpty().let(channel::offer)
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
}
fun <T> ReceiveChannel<T>.debounce(time: Long, unit: TimeUnit = TimeUnit.MILLISECONDS): ReceiveChannel<T> =
Channel<T>(capacity = Channel.CONFLATED).also { channel ->
launch {
var value = receive()
whileSelect {
onTimeout(time, unit) {
channel.offer(value)
value = receive()
true
}
onReceive {
value = it
true
}
}
}
}
@hpuhsp

hpuhsp commented Sep 9, 2020

Copy link
Copy Markdown

the last without launch?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment