0

I am trying to combine LiveData with RxBinding library, I want to use RxSearchView and use switchMap in order to subscribe to the latest observable. I am not sure if my implementation is good. I'll show you my code, please could you tell me if there is another way to achieve this?

disposable = RxSearchView.queryTextChanges(searchView)
    .debounce(300, TimeUnit.MILLISECONDS)
    .switchMap(charSequence -> {
      detailViewModel.loadSearchTask(charSequence);
      return Observable.just(charSequence);
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe();
compositeDisposable.add(disposable);

public void loadSearchTask(CharSequence s) {
    taskInteractor
        .search(s.toString())
        .doOnSubscribe(disposable -> rxSearchLiveData.addDisposable(disposable))
        .subscribe(
            charSequence -> rxSearchLiveData.setValue(Resource.success(charSequence)),
            throwable -> error.setValue(Resource.error(throwable.getMessage(), throwable)));
}

Edit: Should I use a Flowable instead?

tynn
  • 38,113
  • 8
  • 108
  • 143
Deep
  • 189
  • 3
  • 1.) why are you starting a new observable inside a switchMap, it is supposed to be a pure function 2.) use BehaviorSubject instead of LiveData in this case – EpicPandaForce Feb 08 '18 at 03:43

1 Answers1

0

Your implementation has several issues. The first one is, that the first subscribe() doesn't have any consumers defined. The second one is, that you change the thread while it's not necessary.

The biggest issue I see is, that you're subscribing within a mapping. Instead you should just map to the other Observable and handle everything with the single subscription to the chain.

I'll be skipping the Disposable handling, so be aware to add it back as necessary.

RxSearchView.queryTextChanges(searchView)
    .debounce(300, TimeUnit.MILLISECONDS)
    .switchMap(s -> taskInteractor.search(s.toString()))
    .subscribe(
        charSequence -> rxSearchLiveData.setValue(Resource.success(charSequence)),
        throwable -> error.setValue(Resource.error(throwable.getMessage(), throwable)));

As a last note, you can replace the simple lambda disposable -> rxSearchLiveData.addDisposable(disposable) with an even more simple method reference rxSearchLiveData::addDisposable.

tynn
  • 38,113
  • 8
  • 108
  • 143