PublishSubject doOnSubscribe未调用

时间:2016-07-25 16:05:34

标签: android rx-java rx-android

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

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()?我是否误解了主题?

1 个答案:

答案 0 :(得分:8)

不要破坏链条:

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.");
    }
});

在其他方法中使用publishedObservable

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