RxJava总结

just:任意对象转成Observable
示例:Observable.just(new Object())

range(n, m):循环一个数组
示例:Observable.range(1, 4
结果:1,2,3,4
说明:从n到m的连续数组。

retryWhen:失败以后重试机制。可以用于网络请求重试
示例:Observable.retryWhen(new RetryWithDelay(5, 1000)

public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {

        private final int _maxRetries;
        private final int _retryDelayMillis;
        private int _retryCount;

        public RetryWithDelay(final int maxRetries, final int retryDelayMillis) {
            _maxRetries = maxRetries;
            _retryDelayMillis = retryDelayMillis;
            _retryCount = 0;
        }

        // this is a notificationhandler, all that is cared about here
        // is the emission "type" not emission "content"
        // only onNext triggers a re-subscription (onError + onComplete kills it)

        @Override
        public Observable<?> call(Observable<? extends Throwable> inputObservable) {

            // it is critical to use inputObservable in the chain for the result
            // ignoring it and doing your own thing will break the sequence

            return inputObservable.flatMap(new Func1<Throwable, Observable<?>>() {
                @Override
                public Observable<?> call(Throwable throwable) {
                    if (++_retryCount < _maxRetries) {

                        // When this Observable calls onNext, the original
                        // Observable will be retried (i.e. re-subscribed)

                        Timber.d("Retrying in %d ms", _retryCount * _retryDelayMillis);
                        _log(String.format("Retrying in %d ms", _retryCount * _retryDelayMillis));

                        return Observable.timer(_retryCount * _retryDelayMillis,
                              TimeUnit.MILLISECONDS);
                    }

                    Timber.d("Argh! i give up");

                    // Max retries hit. Pass an error so the chain is forcibly completed
                    // only onNext triggers a re-subscription (onError + onComplete kills it)
                    return Observable.error(throwable);
                }
            });
        }
    }

说明:重试5次,间隔1000毫秒。一般用于网络不好的轮询。

MathObservable:算术和聚合对象
使用:MathObservable .sumInteger(Observable.range(1, 5))
说明:1-5所有数相加的各。
结果:1+2+3+4+5 = 15

注意:range,from一级别的方法,都是在一个线程内完成。走到delay这一步,开始开线程执行,如果有List代表一次开List.size条线程开始定时。所以onNext方法相差的时间差为每条线程的时间差

defer:延迟加载。

i=10;
        Observable justObservable = Observable.just(i);
        i=12;
        Observable deferObservable = Observable.defer(new Func0<Observable<Object>>() {
            @Override
            public Observable<Object> call() {
                return Observable.just(i);
            }
        });
        i=15;

        justObservable.subscribe(new Subscriber() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {
                System.out.println("just result:" + o.toString());
            }
        });

        deferObservable.subscribe(new Subscriber() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {
                System.out.println("defer result:" + o.toString());
            }
        });
   }

结果:
just result:10
defer result:15

Observable.range(n,m) .buffer(a,b):Range循环m次,当m=b时默认循环次框架默认7次是相同操作。打印的数组长度为a。

Observable.range(n,m) .buffer(a):循环m次,每次接收容器长度为a。

Observable.range(n,m) .buffer(a, TimeUnit.SECONDS):在a秒内接收数据m个数据,超时的数据不接收

debounce:防止一段时间内做重复的事件
使用:使用在线搜索功能时,一段时间内不操作。防止删除一个字查询一次服务器

combineLatest:合并最近N个结点
用法:

Observable.combineLatest(_emailChangeObservable,
              _passwordChangeObservable,
              _numberChangeObservable,
              new Func3<CharSequence, CharSequence, CharSequence, Boolean>() {
                  @Override
                  public Boolean call(CharSequence newEmail,
                                      CharSequence newPassword,
                                      CharSequence newNumber) {

                      boolean emailValid = !isEmpty(newEmail) &&
                                           EMAIL_ADDRESS.matcher(newEmail).matches();
                      if (!emailValid) {
                          _email.setError("Invalid Email!");
                      }

                      boolean passValid = !isEmpty(newPassword) && newPassword.length() > 8;
                      if (!passValid) {
                          _password.setError("Invalid Password!");
                      }

                      boolean numValid = !isEmpty(newNumber);
                      if (numValid) {
                          int num = Integer.parseInt(newNumber.toString());
                          numValid = num > 0 && num <= 100;
                      }
                      if (!numValid) {
                          _number.setError("Invalid Number!");
                      }

                      return emailValid && passValid && numValid;

                  }
              })//
              .subscribe(new Observer<Boolean>() {
                  @Override
                  public void onCompleted() {
                      Timber.d("completed");
                  }

                  @Override
                  public void onError(Throwable e) {
                      Timber.e(e, "there was an error");
                  }

                  @Override
                  public void onNext(Boolean formValid) {
                      if (formValid) {
                          _btnValidIndicator.setBackgroundColor(getResources().getColor(R.color.blue));
                      } else {
                          _btnValidIndicator.setBackgroundColor(getResources().getColor(R.color.gray));
                      }
                  }
              });

RxTextView.textChanges(_email).skip(1):检测EditText变化,忽略第一次

Observable.concat(Observable… observable):根据顺序执行Observable对象,只要有一个满足就不会执行下一个任务
使用:可以做三级缓存。内存->本地->网络

Observable.merge:合并相同数据,数量不变。不按顺序。多条线程的相同数据,合并到一条线程返回。数据数量不变

Observable.zip:合并不同类型数据。把不同的2种数据合并成一个。数量二合一

toList:转成Observable

你可能感兴趣的:(Rxjava使用记录)