What is Subject.asObservable good for?

2020-08-10 19:06发布

问题:

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;

回答1:

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.



回答2:

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.



标签: rx-java