简体   繁体   English

使用RxJava实现存储库模式

[英]Implementing Repository Pattern With RxJava

I'm trying to figure out a better way to achieve something like repository pattern in RxJava in Android. 我正试图找到一种更好的方法来实现Android中RxJava中的存储库模式。

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. 它还具有refresh布尔参数强制它始终发出网络请求。

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. 问题(或不是),此函数的调用者需要调用它将接收Subscription而不是Observable ,我不能再链接。

Is there a way to make the function return Observable but still have the repository pattern? 有没有办法让函数返回Observable但仍然有存储库模式?

Thanks to akarnokd pointing me out to this article by Dan Lew. 感谢akarnokd向我指出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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM