In a lot of codebases using RxJS I seem to come across the pattern of exposing private Subjects
as Observables
via a getter
or normal getObservable()
function. My question is not why .asObservable()
is used, but instead why it seems so commonly wrapped in a getter/factory function?
asObservable() wrapped in getter/factory function
private readonly _engineInfo$ = new Subject<EngineInfo>();
get engineInfo$() { return this._engineInfo$.asObservable(); }
asObservable() as instance variable
private readonly _engineInfo$ = new Subject<EngineInfo>();
public engineInfo$ = this._engineInfo$.asObservable();
Questions
- My undestanding is that
.asObservable()
creates a newObservable
every time that subscribes to theSubject
. Also the createdObservable
is hot and can be subscribed multiple times. Why would one create multiple anonymous instances ofObservable
, (one for each access/subscription), instead of having just oneObservable
, accessed at one class/service, that all observers subscribe to? - Is there a non-obvious advantage to this
getter/factory function
pattern? - Could it be because of garbage collection or testing/mocking advantages?
So far I'm using the instance variable setup from the second example in all services/classes and everything seems to works as expected, also with multiple observers.