Android RxJava debounce example
This is a RxJava debounce example using a TextView and EditTextView in Android for demonstration. EditTextView is for getting the input, TextView is for displaying the input. Now pretend the EditTextView is a search input box, and the TextView is for sending off the search text over to a server.
While text are being typed into the search input, without using the debounce, it will be sending the search query to the server very quickly. For example, assume the text being typed into the search box is abcdefg, it will be sending 7 search queries to the server, a, ab, abc, abcd, abcde, abcdef, and abcdefg.
Using a debounce will remove some of the unnecessary query strings being sent over to the server. For example, if the debounce is set to have a 300 milliseconds interval, and if the typing speed is 1 letter per 100 millisecond, for the text abcdefg, it will be sending abc, abcdef and abcdefg to the server.
class MainActivity : AppCompatActivity() { private val disposable = CompositeDisposable() private val _textInput = BehaviorSubject.create() private val textInput = _textInput.toFlowable(BackpressureStrategy.LATEST) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) et_input.addTextChangedListener(object: TextWatcher { override fun afterTextChanged(editable: Editable?) { _textInput.onNext(et_input.text.toString()) } override fun beforeTextChanged(charSeq: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(charSeq: CharSequence?, p1: Int, p2: Int, p3: Int) { } }) disposable.add( textInput .debounce(300, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe{ tv_display.text = tv_display.text.toString() + "\n ${Date()}: " + it } ) } override fun onDestroy() { super.onDestroy() disposable.clear() } }
Rxjava dependencies
implementation 'io.reactivex.rxjava2:rxjava:2.2.9' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Search within Codexpedia
Search the entire web