3

I want to cache observable items for subsequent subscriptions but I don't want to cache errors. It seems cache operator also caches throwables. How can I achive that?

ferpar1988
  • 596
  • 2
  • 5
  • 17

1 Answers1

6

There's no way to make cache itself stop caching terminal events (onError and onCompleted). But you can filter out the terminal events before they occur.

I wrote about some ways to handle errors in a post here. Basically, you can use one of the catch operators like onErrorReturn() or onErrorResumeNext() to convert those errors into non-errors.

Alternatively, if you could use materialize() + dematerialize() and filter out any error notifications. But functionally that isn't different from using onErrorResumeNext() with Observable.empty().


As an example, you'd basically do something like this:

observable
  .onErrorResumeNext(throwable -> Observable.empty())
  .cache()

This would filter out errors but then cache the rest.

Dan Lew
  • 85,990
  • 32
  • 182
  • 176
  • Thank you! But I also wonder what if I want to cache result only if the observable completes without an error. I mean if there is an error, cache won't work and it will subscribe the source observable again for the next subscription until the source observable completes without an error. Cache operator subscribes only once I guess. – ferpar1988 Feb 04 '16 at 13:03
  • 1
    You could stick a `retry` before `cache`, which would allow resubscription in case of an error. Might want to research it though, to make sure you aren't infinitely resubscribing. – Dan Lew Feb 04 '16 at 15:28