0

i am new to RxJava. What I want to accomplish is search functionality, where every key press is a request. Also I want be able to call the request explicitly.

So I used

RxTextView.textChanges(editText) .debounce .flatmap(request) for the first part. Everything works.

But when manually calling the request part, I got stuck. I can workaround it to implcitly trigger onTextChange by doing editText.setText(editText.getText) but that feels dirty.

I researched the topic and I found PublishSubject. I extracted the actuall request part in it and looks kinda like this

mPublishSubject.
.doOnNext(.. show progressbars..)
.flatMap(..request..)
.subscribe(.. display data...)

Is there a way I can join textChanges Observable and the request Subject? In other words, how can textChanges stream continue in search subject stream?. Other than calling mPublishSubject.onNext from text observables subscribers onNext.

urSus
  • 12,492
  • 12
  • 69
  • 89

1 Answers1

3

If I understands correctly, you want the request to be fire either by mapping each user text key press from the TextView, or by you're explicit calls at some point independent from the key presses.

What you need is to create two streams of request trigger, one is the RxTextView observable and the other is a PublishSubject like you're suggested, that will emit a value (text string) at your request. then merge this two streams to get one stream that emit texts, and fire an event in response to either text emissions, something like this:

Observable.merge(
        RxTextView.textChanges(editText)
                .debounce(DEBOUNCE_VALUE, TimeUnit.MILLISECONDS),
        mPublishSubject)
            .flatMap(text -> fireRequest(text))
            .subscribe(...);

in order to trigger manually the request, you can have a method like this:

 private void manualRequestTrigger(String text) {
    mPublishSubject.onNext(text);
}

You should also consider using concatMap instead of flatMap as with flatMap the request result will be emitted un ordered, so old request can finish after a newer one, and you will update your UI with old data.

yosriz
  • 10,147
  • 2
  • 24
  • 38