According to the source code in rxjs,
asObservable implementation is like this:
asObservable(): Observable<T> {
const observable = new Observable<T>();
(<any>observable).source = this;
return observable;
}
And I found out, when the source Subjectemits a value using next, the observable also emits the data to the observers which subcribe the observable. This quite much answers my question. But what confuses me is that why we would need asObservable method? Can't we just use Subject itself?
The asObservable method returns an Observable that has the subject as its source:
export class Subject<T> extends Observable<T> implements ISubscription {
...
asObservable(): Observable<T> {
const observable = new Observable<T>();
(<any>observable).source = this;
return observable;
}
}
The point of the method is to create an observable that mirrors the subject, without exposing the subject's methods. That observable can then be returned to a caller.
If the subject itself were to be returned, a caller would be able to invoke the subject's next, error and complete methods. With the observable returned by asObservable, that's not possible.
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