我想实现这样一个功能,用户点击获取数据库数据,若数据库有这个数据,则直接显示本地的,若数据库没有这个数据,就从服务器请求再显示出来。请问一下用rxjava要怎么写呢?
认证高级PHP讲师
1. Write out the function first.
private static Object loadFromCache(String key) { //....本地缓存加载,如果加载失败返回 null } private static Object loadFromServer(String key) { //....通过网络加载,返回数据 Object obj = .... saveToCache(key, obj);//保存到本地缓存 return obj; }
2. Convert blocking methods to RxJava writing
private static Observable<Object> rxLoadFromCache(String key) { return Observable.fromCallable(() -> loadFromCache(key)); } private static Observable<Object> rxLoadFromServer(String key) { return Observable.fromCallable(() -> loadFromServer(key)); }
3.Merge together
public static Observable<Object> rxLoad(String key) { return Observable.concat( rxLoadFromCache(key), rxLoadFromServer(key) ).filter(obj -> obj != null) .take(1); }
4. Call the last method
rxLoad(key) .subscribeOn(Schedulers.io()) .subscribe(obj->{ System.out.println(obj); });
Observable.concat(Observable.just(null), Observable.just(1)) .filter(integer -> integer != null) .take(1) .subscribe(integer -> { //TODO });
Observable.if( () -> { return hasCache; }, Observable.just(cache), Observable.just(database), );
1. Write out the function first.
2. Convert blocking methods to RxJava writing
3.Merge together
4. Call the last method