PublishSubject doOnSubscribe not called



我有一个已注册doOnSubscribedoOnUnsubscribe操作的PublishSubject。如果订阅已完成,则不会调用这两个操作。

private PublishSubject<Long> publishSubject;
private Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    publishSubject = PublishSubject.create();
    publishSubject.doOnSubscribe(new Action0() {
        @Override
        public void call() {
            Log.d("SUBJECT", "Someone subscribed.");
        }
    });
    publishSubject.doOnUnsubscribe(new Action0() {
        @Override
        public void call() {
            Log.d("SUBJECT", "Someone UNsubscribed.");
        }
    });
    Observable.interval(1, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
        @Override
        public void call(final Long tick) {
            publishSubject.onNext(tick);
        }
    });
}
@Override
protected void onResume() {
    super.onResume();
    subscription = publishSubject.subscribe(new Action1<Long>() {
        @Override
        public void call(final Long aLong) {
            Log.d("SUBJECT", "Got tick " + aLong);
        }
    });
}
@Override
protected void onPause() {
    super.onPause();
    subscription.unsubscribe();
}

但在我的logcat中,我只得到"Got tick "消息,没有得到"Someone subscribed"

07-25 17:57:34.110 8753-8965/com.example.plinzen.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-25 17:57:34.954 8753-8964/com.example.plinzen.myapplication D/SUBJECT: Got tick 0
07-25 17:57:35.950 8753-8964/com.example.plinzen.myapplication D/SUBJECT: Got tick 1
07-25 17:57:36.950 8753-8964/com.example.plinzen.myapplication D/SUBJECT: Got tick 2
07-25 17:57:37.950 8753-8964/com.example.plinzen.myapplication D/SUBJECT: Got tick 3
07-25 17:57:38.949 8753-8964/com.example.plinzen.myapplication D/SUBJECT: Got tick 4
07-25 17:57:39.950 8753-8964/com.example.plinzen.myapplication D/SUBJECT: Got tick 5

知道吗,当订阅在onResume()中,而取消订阅在onPause()中时,为什么不调用这些操作?我误解主题了吗?

不要破坏链:

private Observable<Long> publishedObservable;
[...]
PublishSubject<Long> publishSubject = PublishSubject.create();
publishedObservable = publishSubject.doOnSubscribe(new Action0() {
    @Override
    public void call() {
        Log.d("SUBJECT", "Someone subscribed.");
    }
}).doOnUnsubscribe(new Action0() {
    @Override
    public void call() {
        Log.d("SUBJECT", "Someone UNsubscribed.");
    }
});

在其他方法中使用CCD_ 7。

看,在你的代码中,你创建了两个新的Observable,但你直接把它们扔掉了;.doFooBar方法不修改Observable,而是创建一个实现所需行为的新方法。

相关内容

  • 没有找到相关文章

最新更新