使用 RxJava 实现存储库模式 [英] Implementing Repository Pattern With RxJava
问题描述
我正在尝试找出一种更好的方法来实现类似 Android 中 RxJava 中的存储库模式.
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;
}
基本上它会检查是否存储了缓存数据,如果没有,它会发出网络请求.它还有 refresh
布尔参数强制它总是发出网络请求.
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.
问题(或不是)是,这个函数的调用者需要调用它会收到 Subscription
而不是 Observable
,我不能再链接了.
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.
有没有办法让函数返回 Observable
但仍然有存储库模式?
Is there a way to make the function return Observable
but still have the repository pattern?
推荐答案
感谢 akarnokd 向我指出 这篇文章 作者:Dan Lew.
Thanks to akarnokd pointing me out to this article by Dan Lew.
我的最终代码:
public Observable<Data> getData(boolean refresh) {
Observable<Data> obs = Observable.concat(getCache(), requestNetwork());
if(!refresh) {
obs = obs.first(data -> data != null);
}
return obs;
}
这篇关于使用 RxJava 实现存储库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!