-
-
Save a2en/ecfe892c80e962ad052ea4781c331e11 to your computer and use it in GitHub Desktop.
RxJava debounce like operator implementation for kotlin coroutine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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