Rxjava: PublishSubject does not emit values when single() is used

Created on 11 Nov 2014  ·  4Comments  ·  Source: ReactiveX/RxJava

Better to illustrate this with code:

// use case: some api returns subject as an observable, subscription is made
// in other part of the app
// but here I put them together for illustration, to be easily reproducable

PublishSubject<Integer> subject = PublishSubject.create();
subject.single().subscribe(new Observer<Integer>() {
                       @Override
                       public void onCompleted() {

                       }

                       @Override
                       public void onError(Throwable throwable) {

                       }

                       @Override
                       public void onNext(Integer integer) {
                           System.out.println("on next" + integer);
                       }
                   });

 subject.onNext(2);

With the above snippet, nothing will be printed. Note that there is no threading involved, happens on the same thread.
If I remove single() call above, code starts working correctly,prints line.
Or If i add subject.onCompleted() right after subject.onNext(2) call - same, things start to work, even with single() in place, but this is an observation, not a proper fix I guess.

Question

Most helpful comment

You may use take(1) instead to get the first value as soon as it is available and not wait for any other value.

All 4 comments

I am using rxjava 0.20.6

That's how single works. single won't emit the item until it confirms this Observable has exactly one item, or it will emit onError.

You may use take(1) instead to get the first value as soon as it is available and not wait for any other value.

Oh, I didn't know this, so it is not a bug... I just expected that single
would throw on attempt to emit a second item, didn't think that it does
those checks.
11 нояб. 2014 г. 14:52 пользователь "Shixiong Zhu" [email protected]
написал:

That's how single works. single won't emit the item until it confirms
this Observable has exactly one item, or it will emit onError.


Reply to this email directly or view it on GitHub
https://github.com/ReactiveX/RxJava/issues/1861#issuecomment-62542517.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aballano picture aballano  ·  3Comments

nltran picture nltran  ·  4Comments

paulblessing picture paulblessing  ·  3Comments

hoc081098 picture hoc081098  ·  3Comments

yubaokang picture yubaokang  ·  3Comments