Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Subject.asObservable good for?

Tags:

rx-java

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;
like image 742
Paul Woitaschek Avatar asked Feb 02 '16 00:02

Paul Woitaschek


People also ask

When you should use asObservable?

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.

What is the difference between subject and 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.

What is a subject angular?

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.

What are different types of subject in RXJS?

But rxjs offers different types of Subjects, namely: BehaviorSubject, ReplaySubject and AsyncSubject.


1 Answers

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.

like image 145
Dan Lew Avatar answered Oct 07 '22 00:10

Dan Lew