Skip to content

Instantly share code, notes, and snippets.

@MoshDev
Forked from k-kagurazaka/DebounceTest.kt
Created October 17, 2018 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MoshDev/1db645b82637c0459fe7a9c8b26dba60 to your computer and use it in GitHub Desktop.
Save MoshDev/1db645b82637c0459fe7a9c8b26dba60 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
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment