3

I'm trying to figure out a better way to achieve something like repository pattern in RxJava in Android.

Here's what I have so far: (took some code from here)

public Subscription getData(Observer<Data> observer, boolean refresh) {
    Subscription sub = null;

    Data cached = getCachedData();
    if(cached != null) {
        observer.onNext(cached);
        if(refresh) {
            sub = requestNetwork().subscribe(observer);
        } else {
            observer.onCompleted();
        }
    } else {
        sub = requestNetwork().subscribe(observer);
    }

    return sub;
}

Basically it check if there's cached data stored, if not it'll make a network request. It also have refresh boolean parameter force it always make a network request.

The problem (or not) is, the caller of this function needs to call it will receive Subscription instead of Observable, which I can't chain anymore.

Is there a way to make the function return Observable but still have the repository pattern?

Fadli
  • 976
  • 9
  • 24
  • 1
    See http://blog.danlew.net/2015/06/22/loading-data-from-multiple-sources-with-rxjava/ – akarnokd Apr 03 '16 at 10:07
  • Ah, I once opened that article but didn't use it because it used `first` that made the subscriber only got from first source that match the predicate. I forget I could choose **not** to call the `first` operator by utilizing the `refresh` parameter. Thanks! – Fadli Apr 03 '16 at 10:57

1 Answers1

3

Thanks to akarnokd pointing me out to this article by Dan Lew.

My final code:

public Observable<Data> getData(boolean refresh) {
    Observable<Data> obs = Observable.concat(getCache(), requestNetwork());
    if(!refresh) {
        obs = obs.first(data -> data != null);
    }
    return obs;
}
Fadli
  • 976
  • 9
  • 24
  • But this will emit two items when you have an item in the cache and refresh is true.... – Tassos Bassoukos Apr 04 '16 at 14:41
  • @TassosBassoukos I think that is sort of what I wanted. The view will receive the items twice. First the cache then render again the new one from network. – Fadli Apr 04 '16 at 15:35