Reputation: 156
I have been programming for years using Angular and Rxjs, and have always done sibling-to-sibling communication using Subjects from within a service. ie. Emitting and subscribing directly onto a Behavior/Replay/Subject
Someone in my team recently pointed out that on the Angular docs, they use a different approach: https://angular.io/guide/component-interaction#parent-and-children-communicate-using-a-service
They declare the Subjects as private, and then only expose them in an observable form.
Is there any good reason why I should move over to this approach instead? Does it have any actual functional/behavioral difference, or is it just a coding best-practise?
I'm trying to wrap my head around whether this would have an impact on the actual functionality in any scenario, due to Subjects being multicasted and Observables not. Could someone perhaps shed light on that?
If I implement this way of doing it, and have multiple children subscribed to the observable (instead of a subject), and the parent emits a value to the subject, will all of the children get the new value, as if it was a multicasted Subject?
Upvotes: 2
Views: 1168
Reputation: 96899
This doesn't affect functionality. This is used to prevent anyone from calling next()
, error()
or complete()
methods on the Subject instance.
Subjects have internal state and when they emit error or complete they'll never ever emit anything anymore. So you don't want other developers to call these methods because completing or erroring a Subject is probably done only inside the service when the Subject is used.
There's actually one more way to turn Subject into Observable and that is typecasting:
private _subject$ = new Subject<number>();
public subject$: Observable<number> = this._subject$;
RxJS internally uses only typecasting for performance reasons but it's usually better to use asObservable()
because then you don't need to define generics (in this case 'number') again.
Upvotes: 4