Java – RxJava : throw IllegalArgumentException when use ‘first’ operator

RxJava : throw IllegalArgumentException when use ‘first’ operator… here is a solution to the problem.

RxJava : throw IllegalArgumentException when use ‘first’ operator

When I use the Observable.first() operator, I get the IllegalArgumentException message “The sequence contains too many elements”.

Here is a simplified test code that reproduces the exception:

Subject<Integer, Integer> subject = BehaviorSubject.create();

subject.first()
       .subscribe(integer -> subject.onNext(1));

subject.onNext(0);

The code was extracted from a very complex real project, and I don’t think I can easily explain why I need to do this weird thing.

So I just want to ask one question:
Is this a bug with RxJava or am I using it incorrectly?

If used incorrectly, I guess I need to rewrite the logic to avoid these codes.

Thank you so much.

Solution

There is a reentrancy issue with a known bug using the take operator (used by first), and the next version 1.0.15 will include this fix. Sorry, there is no estimated time of arrival above.

By the way, if there is no such error, why would you do this thing in your code? Do you want to signal to other subscribers?

Edit

Workaround:

Any operator that serializes can be used to resolve this error. Perhaps the easiest way is to use BehaviorSubject.create().toSerialized().

Related Problems and Solutions