do操作符可以给Observable的生命周期的各个阶段加上一系列的回调监听,当Observable执行到这个阶段的时候,这些回调就会被触发
示例代码如下:
//cold Obserable
Observable.just("dsfsdsf")
.doOnNext(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.i(TAG,"doOnNext"+s);
}
}).doAfterNext(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.i(TAG,"doAfterNext");
}
}).doOnComplete(new Action() {
@Override
public void run() throws Exception {
Log.i(TAG,"doOnComplete");
}
}).doOnSubscribe(new Consumer<Disposable>() { //订阅之后回调的方法
@Override
public void accept(Disposable disposable) throws Exception {
Log.i(TAG,"doOnSubscribe");
}
}).doAfterTerminate(new Action() {
@Override
public void run() throws Exception {
Log.i(TAG,"doAfterTerminate");
}
}).doFinally(new Action() {
@Override
public void run() throws Exception {
Log.i(TAG,"doFinally");
}
}).doOnEach(new Consumer<Notification<String>>() {
@Override
public void accept(Notification<String> stringNotification) throws Exception {
Log.i(TAG,"doOnEach");
}
}).doOnLifecycle(new Consumer<Disposable>() { //取消订阅
@Override
public void accept(Disposable disposable) throws Exception {
Log.i(TAG,"取消订阅doOnLifecycle");
}
}, new Action() {
@Override
public void run() throws Exception {
Log.i(TAG,"doOnLifecycler-action-run");
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Log.i(TAG,"观察者接受到消息"+s);
}
});
执行结果如下:
网友评论