我有一个使用RxJava和Retrofit2加载数据的活动。为防止每次发生配置更改时触发请求,我使用cache()
运算符。这工作得很好,我可以看到请求只做了一次。问题在于,我不时需要提出新的要求以获取最新的数据。换句话说,我需要使缓存无效。我怎样才能做到这一点?RxJava和Android:如何使使用cache()的observable无效?
的活性是使用存储库发出请求:
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();
}
}
}
查看http://stackoverflow.com/questions/31733455/rxjava-observable-cache-invalidate –
@DaveMoten,感谢您的链接,但如何做到这一点与Retrofit? –