RxJava和Android:如何使使用cache()的可观察对象失效



我有一个使用RxJava和Retrofit2加载数据的Activity。为了防止每次发生配置更改时都触发请求,我使用了cache()操作符。这工作得很好,我可以看到请求只发出一次。问题是,我需要不时地发出新的请求来获取新的数据。换句话说,我需要使缓存无效。我该怎么做呢?

活动正在使用存储库发出请求:

public class Repository {
private final PlaceholderApi api;
private Observable<List<Post>> obs;
private static Repository inst;
public static Repository instance() {
    if (inst == null) {
        inst = new Repository();
    }
    return inst;
}
private Repository() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> System.out.println(message));
    logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
    OkHttpClient okhttp = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .build();
    Retrofit retrofit = new Retrofit.Builder()
            .client(okhttp)
            .addConverterFactory(MoshiConverterFactory.create())
            .baseUrl("http://jsonplaceholder.typicode.com/")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
            .build();
    api = retrofit.create(PlaceholderApi.class);
}
public Observable<List<Post>> getAll() {
    if (obs == null) {
        obs = api.getPosts().cache();
    }
    return obs;
}
}

活动代码:

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Subscription sub1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sub1 = Repository.instance().getAll().subscribe(/* handle posts list */);
}
@Override
protected void onDestroy() {
    super.onDestroy();
    if (sub1 != null && !sub1.isUnsubscribed()) {
        sub1.unsubscribe();
    }
}
}

下面是一个使用OnSubscribeRefreshingCache包装器类的例子,来自Dave Moten的回答:

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Subscription sub1;
private OnSubscribeRefreshingCache<List<Post>> postCache;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        postCache = new OnSubscribeRefreshingCache(Repository.instance().getAll());
        sub1 = subscribe(Observable.create(postCache));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sub1 != null && !sub1.isUnsubscribed()) {
            sub1.unsubscribe();
        }
    }
    private Subscription subscribe(Observable<List<Post> postObservable){
        return postObservable.subscribe(/* handle posts list */);
    }
    private void invalidateCache(){
        postCache.reset();
        sub1 = subscribe(Observable.create(postCache));
    }
}

然后在Activity生命周期方法中调用invalidateCache()方法或任何适合您的方法。

另一种解决问题的方法是使用OperatorFreeze(没有操作符缓存),如果你使用持久呈现器。这个操作符可以在配置发生变化时暂停你的Observable,并在activity重新创建时恢复它。你也不需要在存储库中存储observable

相关内容

  • 没有找到相关文章

最新更新