prom85
prom85

Reputation: 17788

RxJava - toList and still emits more than one item

How is following possible:

Observable<Data> obs = ...;
List<Data> data = obs
    .toList()
    .toObservable()
    .singleOrError() // <= this line throws the exception
    .blockingGet();

My code sometimes throws a java.lang.IllegalArgumentException: Sequence contains more than one element!. Shouldn't I ALWAYS get a single List<Data> element in my case (or null) but never multiple elements?

Upvotes: 0

Views: 2855

Answers (3)

Devel Phoenix
Devel Phoenix

Reputation: 1

You should use .firstOrError bcos .singleOrError is not expecting new items from the upstream. And fails as it should. Especially if you have list there.

Upvotes: 0

solidak
solidak

Reputation: 5081

I'm curious, why are you using .toList(), where the return is a Single, and then changing it to an observable, just to check whether its a single or error it out?

Why not just do this:

Observable<Data> obs = ...;
List<Data> data = obs
    .toList()
    .blockingGet();

P.S: I know my answer could be wrong. Correct me if that's the case, but I wanted to post it since a comment would not allow proper formatting.

Upvotes: 0

Kiskae
Kiskae

Reputation: 25573

The exception should be impossible given the fact that toList returns a Single in RxJava2. So it might be caused by something upstream not properly implementing the Rx Protocol.

I suggest adding a doOnNext logging call between the toObservable and singleOrError to see what this potential second emission would be.

Upvotes: 2

Related Questions