Observable vs Subject and asObservable

巧了我就是萌 提交于 2019-11-29 00:48:12

问题


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 service that I can use .next() on in various places in my service class. I am wondering if this is the proper way to do it:

private myObservable = new Subject<T>();
public myObservable$: Observable<T> = this.myObservable.asObservable();
  • The user can subscribe to myObservable$
  • I can usemyObservable.next(...);

It works perfectly but I am experience enough to know that I may just be being an unwitting idiot (RxJS is huge). Is this correct pattern and correct object for said use case?


回答1:


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?




回答2:


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);
      }


来源:https://stackoverflow.com/questions/48935584/observable-vs-subject-and-asobservable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!