Search code examples
javarx-java2

rxjava PublishSubject second time not subscribe


private static PublishSubject<UserBean> mPublishSubject;
private static AtomicBoolean mRefreshing = new AtomicBoolean(false);
private static Observable<UserBean> mTokenObservable;

public Observable<UserBean> getNetTokenLocked() {
    if (mRefreshing.compareAndSet(false, true)) {
        Log.e(TAG, "first    request");
        mTokenObservable.subscribe(mPublishSubject);
    } else {
        Log.e(TAG, "else  wait back");
    }
    return mPublishSubject;                         //second didn't return  
}

return mPublishSubject; <- I want to be able to give me the previous data for the second time


Solution

  • Publish Subject emits all the subsequent items of the source Observable at the time of subscription. If you want to emit all the items of the source Observable, regardless of when the subscriber subscribes, use Replay Subject.

    PublishSubject<Integer> source = PublishSubject.create();
    
    // It will get 1, 2, 3, 4 and onComplete
    source.subscribe(getFirstObserver()); 
    
    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
    
    // It will get 4 and onComplete for second observer also.
    source.subscribe(getSecondObserver());
    
    source.onNext(4);
    source.onComplete();