基于rxjava1.1.0
用例代码↓
Observable<String> observable1 = Observable.create(new Observable.OnSubscribe<String>() {
⑦
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("1");
subscriber.onCompleted();
}
});
Subscriber<Integer> subscriber1 = new Subscriber<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
⑩
@Override
public void onNext(Integer s) {
Log.e("haha",s+"");
}
};
observable1.map(new Func1<String, Integer>() {
⑨
@Override
public Integer call(String s) {
return Integer.valueOf(s);
}
}).subscribe(subscriber1);
lift精简源码↓
public final <R> Observable<R> lift(final Operator<? extends R, ? super T> operator) {
①
//create Observable2 OnSubscribe2
return new Observable<R>(new OnSubscribe<R>() {
②
@Override
public void call(Subscriber<? super R> o) {
③
Subscriber<? super T> st = hook.onLift(operator).call(o);
st.onStart();
⑥
onSubscribe.call(st);
}
});
}
//hook.onLift(operator)
public <T, R> Operator<? extends R, ? super T> onLift(final Operator<? extends R, ? super T> lift) {
return lift;
}
OperatorMap精简源码↓
public final class OperatorMap<T, R> implements Operator<R, T> {
private final Func1<? super T, ? extends R> transformer;
public OperatorMap(Func1<? super T, ? extends R> transformer) {
this.transformer = transformer;
}
④
@Override
public Subscriber<? super T> call(final Subscriber<? super R> o) {
⑤
//create Subscriber2
return new Subscriber<T>(o) {
⑧
@Override
public void onNext(T t) {
o.onNext(transformer.call(t));
}
};
}
}
执行observable1.map.subscribe(subscriber1);调用顺序链由①→⑩
分解操作
observable1.map.subscribe(subscriber1) = observable1.lift(operatorMap).subscribe(subscriber1)
此时没有发生订阅关系由①开始创建了一个observable2 和对应的onSubscribe2
相当于observable2 .subscribe(subscriber1),执行上述代码产生订阅关系,由文章http://www.jianshu.com/p/394debafe192知道会执行observable2 .onSubscribe2.call(subscriber1)即②处
继续执行③OperatorMap的call方法④处会在⑤创建subscriber2,继续执行⑥此处onSubscribe.call(st) = onSubscribe1.call(subscriber2),执行onSubscribe1的call⑦处执行subscriber2.onNext("1");即⑧处
在⑧处中onNext方法里执行了o.onNext(transformer.call(t)),其中transformer.call(t)调用的是⑨处的方法转化数据,o.onNext = subscriber1.onNext 即执行到⑩处
至此流程完结
分析lift(operator) 在整个过程中的作用
operator创建了新的subscriber2 并持有subscriber1的引用
lift创建了一个新的observable2 和onSubscribe2并在call方法里把源onSubscribe1和新的subscriber2 关联起来 元数据的发射由subscriber2 接收 由于operator中持有subscriber1的引用 可以自定义处理方式,即subscriber2 可以做转化然后由源subscriber1发射出去,即operator是subscriber的一种代理用户通过选择不同的operator的实现来进行不同的数据处理方式
lift相当于一个中间层创建的Observable最终会流向源Observable
网友评论