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;
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;
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.
I needed to "remember" the emitted value for subsequent Subscribers to use, so I used a BehaviourSubject. I chose to return an Observable so that Subscribers didn't try to send data to it.