Why does RxJava need asObservable
?
Technically each Subject is already an Observable. What is the advantage of it over just casting it like
Observable obs = subject;
asObservable() The purpose of this is to prevent leaking the "observer side" of the Subject out of an API. Basically to prevent a leaky abstraction when you don't want people to be able to "next" into the resulting observable.
The main difference between an Observable and a Subject is that a plain Observable by default is unicast. It means that each subscribed Observer owns an independent execution of the Observable. On the other hand, Subjects are multicast. A Subject is like an Observable, but it can multicast to many Observers.
A Subject is a special type of Observable that allows values to be multicasted to many Observers. The subjects are also observers because they can subscribe to another observable and get value from it, which it will multicast to all of its subscribers. Basically, a subject can act as both observable & an observer.
But rxjs offers different types of Subjects, namely: BehaviorSubject, ReplaySubject and AsyncSubject.
If you were to just cast the Subject
to an Observable
then you could still use it as a Subject
by casting it back:
PublishSubject<String> subject = PublishSubject.create();
subject.subscribe(System.out::println);
Observable<String> observable = subject;
((PublishSubject<String>) observable).onNext("Hello, world!");
Observable.asObservable()
doesn't actually cast the type to Observable
; it actually wraps the current Observable
. That means that no one has access to the upstream Observable
.
The same code using asObservable()
crashes with a ClassCastException
:
PublishSubject<String> subject = PublishSubject.create();
subject.subscribe(System.out::println);
Observable<String> observable = subject.asObservable();
((PublishSubject<String>) observable).onNext("Hello, world!");
It's a lot like the final
modifier. Sometimes you don't want code to have 100% control over everything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With