Reputation: 976
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?
Upvotes: 3
Views: 2956
Reputation: 976
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;
}
Upvotes: 3