How to use void Subject in RxJava2?

3.2k views Asked by At

I've managed to create it this way:

private final PublishSubject<Void> subject = PublishSubject.create();

But how to pass value to it in onNext(T t)? I can't pass null to it, cause it will throw an exception. onComplete isn't an option too.

2

There are 2 answers

2
akarnokd On BEST ANSWER

Nulls are generally not allowed in 2.x thus a Void type won't let you emit any onNext(null) unlike 1.x. If you think you need Void as your element type, it indicates you don't care about what elements are just that you want to react to something over and over.

For this case, you can instead use any other type and signal any value. In the wiki there is an example you can adapt:

enum Irrelevant { INSTANCE; }

PublishSubject<Irrelevant > source = PublishSubject.create();

source.subscribe(e -> { /* Ignored. */ }, Throwable::printStackTrace);

source.onNext(Irrelevant.INSTANCE);
source.onNext(Irrelevant.INSTANCE);
1
Diego Alvis On

In Kotlin you can use Unit:

val source = PublishSubject.create<Unit>()

source.onNext(Unit)