Search code examples
androidsearchrx-java2debouncingandroid-textwatcher

Combine both on text change and debounce in rxjava for edittext


I've been using rxjava2 for a while but mostly kind of a boilerplate, I didn't clearly know its features.

I supposed to create a search Edittext which call method after sometime. I got it working by the following code:

RxTextView.textChanges(edittextSearch)
                .filter(charSequence -> charSequence.length() > 3)
                .debounce(800, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(string -> {
                    search(string.toString());
                }, error -> {
                    Log.e("ERROR","ERROR LISTENING: " + error.getMessage());
                });

However, I need one more feature for this EditText, which is as soon as I type, even with just one character, I would display an "X" icon to clear the input, or hide it if user manually delete all text.

I don't know if the textChanges method above could do that or I have to add another text watcher for the edittextSearch

Thank you for your time.


Solution

  • You can achieve what you want by using a TextInputLayout and adding app:endIconMode="clear_text". It's part of the material design library, there are plenty of guides on how to use them.

    This will automatically add a clear icon when the user begins typing, clicking the icon will clear the text and update your textChanges observable.