Observable vs Subject and asObservable

前端 未结 2 933
粉色の甜心
粉色の甜心 2020-12-14 02:57

I am learning RxJs, I am seeking confirmation or correction on my assumption.

I am trying to make a public read only observable in a servic

相关标签:
2条回答
  • 2020-12-14 03:56

    What you're doing is correct. There's however still a little shorter notation. Since Subject is already an Observable (it inherits the Observable class) you can leave the type checking to TypeScript:

    private myObservable = new Subject<T>();
    public myObservable$: Observable<T> = this.myObservable;
    

    Any consumer of your service can subscribe to myObservable$ but won't be able to call myObservable$.next() because TypeScript won't let you do that (Observable class doesn't have any next() method).

    This is actually the recommended way of doing it and RxJS internally never uses asObservable anyway. For more detailed discussion see:

    • https://github.com/ReactiveX/rxjs/pull/2408

    • https://github.com/ReactiveX/rxjs/issues/2391

    See a very similar question: Should rxjs subjects be public in the class?

    0 讨论(0)
  • 2020-12-14 04:01

    In project we are using this kind of Observables, this is giving you proper encapsulation to your private observable, but you still can call next() using some public method.

          private sourceName = new Subject<T>();
          name = this.sourceProductName.asObservable();
    
          sendName(item: T) {
            this.sourceName.next(item);
          }
    
    0 讨论(0)
提交回复
热议问题