Reputation: 549
Using RxJava3, given an Observable
and a Subject
, I can subscribe the Subject to the Observable:
observable.subscribe(subject); // returns void, not a subscription
Later, my Subject is not interested anymore in the Observable, how to unsubscribe it from the Observable ?
Upvotes: 1
Views: 715
Reputation: 94961
I think the simplest option is to use an overload of subscribe
that returns a Disposable
, and have each handler call the appropriate method on your Subject
, like this:
Disposable d = observable
.subscribe(subject::onNext, subject::onError, subject::onComplete);
// Later
d.dispose();
You could also create a DisposableObserver
that forwards all messages to the Subject
, and use subscribeWith
instead of subscribe
, though it's more verbose:
Disposable d = observable
.subscribeWith(new DisposableObserver<Integer>() {
@Override public void onStart() {
}
@Override public void onNext(Integer t) {
subject.onNext(t);
}
@Override public void onError(Throwable t) {
subject.onError(t);
}
@Override public void onComplete() {
subject.onComplete();
}
});
I'm not aware of any cleaner options, and this issue from the RxJava bug tracker seems to back that up, though it is targeted at RxJava2.
Upvotes: 3