Skip to content

Instantly share code, notes, and snippets.

@snijsure
Created August 29, 2018 17:31
Show Gist options
  • Save snijsure/1e2804feaf93fe72ba1446272a118a8c to your computer and use it in GitHub Desktop.
Save snijsure/1e2804feaf93fe72ba1446272a118a8c to your computer and use it in GitHub Desktop.
Implement search using RxJava
public class RxSearchObservable {
public static Observable<String> fromView(SearchView searchView) {
final PublishSubject<String> subject = PublishSubject.create();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
subject.onComplete();
return true;
}
@Override
public boolean onQueryTextChange(String text) {
subject.onNext(text);
return true;
}
});
return subject;
}
}
RxSearchObservable.fromView(searchView)
.debounce(300, TimeUnit.MILLISECONDS)
.filter(new Predicate<String>() {
@Override
public boolean test(String text) throws Exception {
if (text.isEmpty()) {
return false;
} else {
return true;
}
}
})
.distinctUntilChanged()
.switchMap(new Function<String, ObservableSource<String>>() {
@Override
public ObservableSource<String> apply(String query) throws Exception {
return dataFromNetwork(query);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>() {
@Override
public void accept(String result) throws Exception {
textViewResult.setText(result);
}
});
@snijsure
Copy link
Author

  • The debounce operator handles the case when the user types “a”, “ab”, “abc”, in a very short time.
  • 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.
  • SwitchMap: SwitchMap operator is used to avoid the network call results which are no longer needed. Let say the last search query was “ab” and there is an ongoing network call for “ab” and the user types “abc”, so we are going to throw away results for search ab

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment