1

I have the following requirement:

  1. Multiple observers (fragments) need to subscribe to a data source.
  2. Activity will start a network request. Once the request is successful, each observer will receive the result.

I've trying to do it using cache / publish operators, but the issue is when initial request returns an error. At this point I wish to reset the stream and subsequent calls to the method should run a new network request instead of returning an error each time.

Here's what I have currently.

private Flowable<List<Data>> dataObservable;

private Flowable<List<Data>> getData(){
    if(dataObservable == null){
        dataObservable = apiService.getData()
                .doOnError(throwable -> {
                    dataObservable = null;
                })
                .cache();
    }
    return dataObservable;
}

This works, but the code feels wrong. There's got to be a better way.

Tomislav Turcic
  • 879
  • 1
  • 11
  • 24

2 Answers2

0

You can define the observable ahead of time, and it won't actually do anything until something subscribes to it. That's one less null value to worry about.

You can use the retry() operator, or a variant of it, to automatically retry the network operation on an error.

Finally, the cache() operator will ensure that only one network connection subscription is active. Each subscriber will get any updates from the observable, and will be oblivious to any network errors experienced.

Flowable<List<Data>> dataObservable = apiService.getData()
  .retry()
  .cache();
Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42
  • Issue is that retry() operator keeps on retrying indefinitely, without any input from me. – Tomislav Turcic Oct 23 '17 at 16:17
  • There are several `retry()` operators taking various arguments. This is a good introduction: http://blog.danlew.net/2016/01/25/rxjavas-repeatwhen-and-retrywhen-explained/ – Bob Dalgleish Oct 23 '17 at 17:13
0

Apparently there is no operator for that.

The issue was discussed at Observable, retry on error and cache only if completed and Plato created a nice tiny lib for that platoblm/rx-onerror-retry-cache.

Iwo Banas
  • 892
  • 8
  • 12