Implement search using Rx.Android

Excellence is not enough!

Implement search using Rx.Android

Rx Android

In this article we are gonna learn how to implement a handy search tool using RxAndroid.

So let’s take a look into the UI code:

private val searchSubject = PublishSubject.create<String>()

private fun initUi() {
        svMain.setOnClickListener {
            svMain.isIconified = !svMain.isIconified

        svMain.setOnQueryTextListener(object  : SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                Utils.hideKeyboard(context!! , svMain)
                return true

            override fun onQueryTextChange(newText: String?): Boolean {
                return true





In the code above I declared a PublishSubject object to use in the generation of search strings. then I set a QueryTextListener for the Search View to track user’s entries.

So now let’s take a look into view models code:

fun subscribeToSeach(searchSubject: PublishSubject<String>) {
        .debounce(550  , TimeUnit.MILLISECONDS)
        .filter {
        .subscribe {


fun nextSearch(search : String ) {

Then we pass the subject object we created in the View layer into the view model, now the Rx time!.

debounce :The debounce operator handles the case when the user types “a”, “ab”, “abc”, in a very short time. So there will be too much network calls. But the user is finally interested in the result of the search “abc”. So, you must discard the results of “a” and “ab”. Ideally, there should be no network calls for “a” and “ab” as the user typed those in very short time. So, the debounce operator comes to the rescue. The debounce will wait for the provided time for doing anything, if any other search query comes in between that time, it will ignore the previous item and start waiting for that time again with the new search query. If nothing new comes in that given constant time, it will proceed with that search query for further processing. So, debounce only emit an item from an Observable if a particular timespan has passed without it emitting an another item.

filter : The filter operator is used to filter the unwanted string like empty string in this case to avoid the unnecessary network call.

distinctUntilChanged : The distinctUntilChanged operator is used to avoid the duplicate network calls. Let say the last on-going search query was “abc” and the user deleted “c” and again typed “c”. So again it’s “abc”. So if the network call is already going on with the search query “abc”, it will not make the duplicate call again with the search query “abc”. So, distinctUntilChanged suppress duplicate consecutive items emitted by the source Observable.

That’s it, now you have a simple and handy search function to add into our app.



Sources :