These are chat archives for ReactiveX/RxJava

11th
Nov 2015
Adam
@AdamCopperfield
Nov 11 2015 08:41
I have two sources of a data: a netowrk and a cache.
User needs the data from the network, but first he needs to see the data from the cache.
Cache may throw CacheNotAvailableException. In this case, obtaining data from the network should be continued.
Is there a best way to do it than
obsFromNetwork.startWith(obsFromCache.onErrorResumeNext(obsFromNetwork))?
David Stemmer
@weefbellington
Nov 11 2015 14:23
@AdamCopperfield switchIfEmpty looks like it might fit the bill: http://reactivex.io/documentation/operators/defaultifempty.html
Dorus
@Dorus
Nov 11 2015 14:25
Or amb with a delay on the network, but switchIfEmpty looks more elegant.
David Stemmer
@weefbellington
Nov 11 2015 14:34
I think you might want to check the type of error before using onErrorResumeNext
David Stemmer
@weefbellington
Nov 11 2015 14:41
Func1<Throwable, Observable> useNetworkIfCacheUnavailable = e ->
   e instanceOf CacheNotAvailableException ?
      networkObservable :
      Observable.error(e);
Observable dataSource = cacheObservable
   .onErrorResumeNext(useNetworkIfCacheUnavailable)
   .switchIfEmpty(networkObservable);
Adam
@AdamCopperfield
Nov 11 2015 15:41
@weefbellington how to keep obtaining from the network even if cacheObservable terminated successfully?
Dorus
@Dorus
Nov 11 2015 15:41
use defer i think
David Stemmer
@weefbellington
Nov 11 2015 15:46
@AdamCopperfield if cacheObservable terminates successfully but it’s empty, the network observable should fire
unless I am misunderstanding switchIfEmpty
@Dorus why is defer necessary here?
Dorus
@Dorus
Nov 11 2015 15:47
You understood switchIfEmpty, but it's entirely possible networkObservable starts the network connection on creation, not on subscription (what is wrong), Observable.defer fixes this by only creating the networkObservable when there is a subscription to it.
Or at least, that's my guess ;)
David Stemmer
@weefbellington
Nov 11 2015 15:49
ah, I hadn’t considered the possibility that the networkObservable would open the connection eagerly
Dorus
@Dorus
Nov 11 2015 15:51
Rereading what i wrote up there: I mean eagerly connecting is wrong, and waiting for a subscription is correct. I wrote it a bit awkward.
David Stemmer
@weefbellington
Nov 11 2015 15:52
I understood ya
Adam
@AdamCopperfield
Nov 11 2015 15:56
yeah thanks guys, I understood