Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs: Is the observable born out of asObservable method of Subject the same as the source Subject?

Tags:

rxjs

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?

like image 600
DongBin Kim Avatar asked Nov 28 '25 01:11

DongBin Kim


1 Answers

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.

like image 123
cartant Avatar answered Nov 29 '25 15:11

cartant