Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

javascript - Observable vs Subject and asObservable

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...