2016-07-25 120 views
1

我有一個PublishSubject註冊doOnSubscribedoOnUnsubscribe行動。如果訂閱完成,這兩個操作都不會被調用。發佈主題doOn訂閱不叫

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()?我誤解了主題話題嗎?

+0

解釋*如果訂閱完成,這兩個操作都不會被調用* –

回答

6

不要打破鏈:

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

在代碼中,您可以創建兩個新的Observables,但是直接丟棄它們; .doFooBar方法不會修改Observable,它們會創建一個實現所需行爲的新方法。

+0

Oooh,我的愚蠢錯誤!感謝您的幫助 – Christopher