先来横向比照一下
Observer有三个办法
Subscriber 有四个办法
- onStart(可有选择性的重写)
- onCompleted
- onError
- onNext
Action 是 RxJava 的一个接口,罕用的有Action0和Action1
Action0
public interface Action0 extends Action { void call();}
Action1
public interface Action1<T> extends Action { void call(T t);}
- 而后上关联(subscribe)源码,这个是只有onNext一个参数的重写办法
- 其余的也相似,依据参数外部不同间接调用对应办法
public final Subscription subscribe(final Action1<? super T> onNext) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } // 如果传入的Action 不为空,则进行转换,源码里进行调用onNext办法 return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { throw new OnErrorNotImplementedException(e); } @Override public final void onNext(T args) { //看这句,在这里间接调用参数onNext里Action的call办法 onNext.call(args); } });}
- 所以,源码上做了一些简写,一些状况下Action齐全能够代替Subscriber,还更加灵便
咱们开始编故事(撸码)
//新建Action 设置泛型为StringAction1<String> onNextAction = new Action1<String>() { @Override public void call(String s) { LogUtils.e(s); }};//把小明和小花关联起来Observable.just("Hello", "World").subscribe(onNextAction);
到重点了
Action1<String> onNextAction = new Action1<String>() { @Override public void call(String s) { LogUtils.e(s); }};Action1<Throwable> onErrorAction = new Action1<Throwable>() { @Override public void call(Throwable throwable) { LogUtils.e(throwable.getMessage()); }};Action0 actionCompleted = new Action0() { @Override public void call() { LogUtils.e("Completed"); }};//第一种调用模式Observable.just("Hello", "World").subscribe(onNextAction);//第二种调用模式Observable.just("Hello", "World").subscribe(onNextAction,onErrorAction);//全副调用模式Observable.just("Hello", "World").subscribe(onNextAction,onErrorAction,actionCompleted);