Effective way of implementing Instant Search with RxJava2

Haris Krasniqi
MindOrks
Published in
2 min readApr 19, 2017

RxJava is a very powerful library for asynchronous jobs offering variety of features which can be combined and implemented in multiple ways.

This article focuses on how we can use some of those features for handling an Instant Search feature effectively.

Suppose we make an instant search feature for searching images usingSearchViewas below and we make a request on onQueryTextChange:

searchView.setOnQueryTextListener(
new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
//Here we request a search
presenter.instantSearch(newText);
return false;
}
});

On the other side we do the magic by holding a reference to PublishSubject and calling onNext() whenever we request a new search:

  • We create a PublishSubject for the search term
  • On onQueryTextChange we invoke onNext("searchTerm")
  • Apply debounce() to reduce requests frequency
  • Apply distinctUtilChanged() to ignore making same requests
  • Apply switchMap() to cancel/discard previous requests and return only the latest response
  • Subscribe to DisposableObserver to consume response
PublishSubject publishSubject;...@Override
public void instantSearch(String searchTerm) {
if (publishSubject == null) {
publishSubject = PublishSubject.create();
publishSubject
.debounce(300, TimeUnit.MILLISECONDS)
.distinctUntilChanged()
.switchMap(searchValue -> model.getImages(searchTerm)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()))
.subscribeWith(new DisposableObserver<YourResponse>() {
@Override
public void onNext(YourResponseget response) {
//Update View here
}
@Override
public void onError(Throwable e) {
//On error
}
@Override
public void onComplete() {
//On complete
}
});
}
publishSubject.onNext(searchTerm);
}

model.getImages(..) is a request which returns an Observable<…>

This way with the help of RxJava features we prevent overloading server with requests and we handle responses more efficiently.

If you liked this article, be sure to click ❤ below and check my Play Store Apps

--

--