Dmitriy Voronin
Dmitriy Voronin

Reputation: 649

RxJava infinite stream best practice

In android app i have this case:

Listen to my editText with observable:

WidgetObservable.text(myEditText, false)
    .map { it.text().toString() }
    .debounce(800, TimeUnit.MILLISECONDS, Schedulers.io())

Then i need to send network request with string emitted by observable:

    .flatMap { networkObservable.subscribeOn(Schedulers.io()) }

My question is: what is the best possible way to write infinite stream of these network results. Errors handled by UI.

Unsubscription done with AppObservable.bindActivity() wrapper

I ended up attaching materialize() operator to network observable, and then handling it like:

    .subscribe{
          when (it.getKind()) {
            Kind.OnNext  -> text.setText(it.getValue())
            Kind.OnError -> text.setText(it.getThrowable().getMessage())
          }
    }

Do you know better way, or its just fine? At least it works.

P.S. another useful case will be Refresh button clicks flatMap'ed to network calls

Upvotes: 0

Views: 823

Answers (1)

zsxwing
zsxwing

Reputation: 20836

You can use onErrorResumeNext to recovery your Observable from a failure. E.g.,

WidgetObservable.text(myEditText, false)
    .map { it.text().toString() }
    .debounce(800, TimeUnit.MILLISECONDS, Schedulers.io())
    .flatMap {
          networkObservable.subscribeOn(Schedulers.io())
                           .onErrorResumeNext(t -> t.getMessage())
    }

Upvotes: 1

Related Questions