Rxjava(其他)--doOnSubscribe原理

本文介绍了RxJava中doOnSubscribe操作符的使用方法及其实现原理。doOnSubscribe通常用于执行初始化操作,如设置资源或开启监听等。文章通过示例代码详细解释了doOnSubscribe的工作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

doOnSubscribe一般用于执行一些初始化操作,我们看其实现原理

demo

      Observable.just(1).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                System.out.println("<<<<<<subscribe thread id = " + Thread.currentThread().getId());
            }
        }).subscribe(new Action1<Integer>() {
                     @Override
                     public void call(Integer integer) {
                         System.out.println("<<<<<<subscribe thread id = " + Thread.currentThread().getId
                                 ());
                     }
                 });
doOnSubscribe用于在call之前执行一些初始化操作

我们看下其实现原理

 public final Observable<T> doOnSubscribe(final Action0 subscribe) {
        return lift(new OperatorDoOnSubscribe<T>(subscribe));
    }
新建了一个OperatorDoOnSubscribe并调用lift

 public final <R> Observable<R> lift(final Operator<? extends R, ? super T> operator) {
        return create(new OnSubscribeLift<T, R>(onSubscribe, operator));
    }
创建了一个OnSubscribeLift,然后当我们订阅的时候会调用它的call方法
 public void call(Subscriber<? super R> o) {
        try {
            Subscriber<? super T> st = RxJavaHooks.onObservableLift(operator).call(o);
            try {
                // new Subscriber created and being subscribed with so 'onStart' it
                st.onStart();
                parent.call(st);
            } catch (Throwable e) {
                // localized capture of errors rather than it skipping all operators
                // and ending up in the try/catch of the subscribe method which then
                // prevents onErrorResumeNext and other similar approaches to error handling
                Exceptions.throwIfFatal(e);
                st.onError(e);
            }
        } catch (Throwable e) {
            Exceptions.throwIfFatal(e);
            // if the lift function failed all we can do is pass the error to the final Subscriber
            // as we don't have the operator available to us
            o.onError(e);
        }
    }
这里的operator就是我们前面的OperatorDoOnSubscribe,这里调用它的call方法

  public Subscriber<? super T> call(final Subscriber<? super T> child) {
        subscribe.call();
        // Pass through since this operator is for notification only, there is
        // no change to the stream whatsoever.
        return Subscribers.wrap(child);
    }

这里的subscribe就是我们的doOnSubscribe的回调函数,当有多个doOnSubscribe时,在调用OnSubscribeLift的parent.call(st)时会先调用他的doOnSubscribe的回调,所以doOnSubscribe在后的先调。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值