Open In App

Implement Search Using RxJava Operators

Nowadays, most of the programs we use in our everyday lives include a search option that allows us to easily find what we’re looking for. As a result, having a search tool is critical. And it is our job as developers to implement it better. Let’s look at how to do it better with the RxJava Operators.

Image 1. The RxSearch as in GfG.

The following RxJava features will be used to build this search feature:



Prerequisite: We will need to know the basic RxJava functions, as implementing search is somewhat high order.

Whoa! although this may sound like implementing a search is really tough, but NO. It’s really easy when we do it stepwise as mentioned below in this article, and you will be up and running in no time. Moreover, all the terms above are linked to other awesome GfG articles to extend your learning! Without further ado, let’s start.



Step by Step Implementation

Step #1: Making search view Observable

First and foremost, you must make the SearchView visible. Let’s use the PublishSubject to make the SearchView observable. Here we are making use of the Android SearchView. The view may be anything that looks like EditText. It’s only that you’ll need to build the text change listener to make that view visible.




public class GfGSearch {
    public static Observable<String> fromView(SearchView gfgSearch) {
        final gfgArticle<String> article = gfgArticle.create();
        gfgSearch.setOnQueryTextListener(new gfgSearch.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                article.onComplete();
                return true;
            }
  
            @Override
            public boolean onQueryTextChange(String text) {
                article.onNext(text);
                return true;
            }
        });
  
        return article;
    }
}

Step #2: Applying the Operators

You must use the following operations on that SearchView observable:




@Override
public ObservableSource<String> apply(String query)
        {
            return dataFromNetwork(query)
                .doOnError(throwable
                           -> {
                              // Exception Handling
                           })
                .onErrorReturn(throwable -> "");
        }
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<String>() {
        @Override public void accept(String result)
        {
            searchResult.setText(result);
        }
    });
RxGfGSearch.fromView(searchView)
    .debounce(200, TimeUnit.MILLISECONDS)
    .filter(new Predicate<String>() {
        @Override public boolean test(String text)
        {
            if (text.isEmpty()) {
                searchResult.setText("Spandan");
                return false;
            }
            else {
                return true;
            }
        }
    })
    .distinctUntilChanged()
    .switchMap(new Function<String, ObservableSource<String> >() {

Understanding the Terms which we used in the above code:

DistinctUntilChanged: The distinctUntilChanged operator prevents repeated network calls. Assume the most recent ongoing search query was “abc,” and the user erased “c” before typing “c” again. So it’s “abc” once more. So, if a network call is already in progress with the search query “abc,” it will not initiate a duplicate call with the search query “abc.” As a result, distinctUntilChanged prevents the source Observable from emitting duplicate successive items.

Geek Tip #1: Returns a new Observable by applying the given function to each item emitted by the source.

Conclusion

And yes, that’s pretty much it for this article, by this you would now be able to implement a RxSearch using RxJava, this search is used in many places throughout like Netflix, Google, and even Geeks for Geeks. Imagine how tough the world would be without Rx!

Always Remember:
There is something for everything in RxJava!


Article Tags :