android - rxjava 条件判断
PHP中文网
PHP中文网 2017-04-17 17:52:11
0
3
632

我想实现这样一个功能,用户点击获取数据库数据,若数据库有这个数据,则直接显示本地的,若数据库没有这个数据,就从服务器请求再显示出来。
请问一下用rxjava要怎么写呢?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
Ty80

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),
);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template