For example, i have such code
get isChart(): Observable<boolean> {
return this.isTemperatureChart.pipe(
withLatestFrom(this.isHypertensionChart),
map(([isTemperatureChart, isHypertensionChart]) => isTemperatureChart ||
isHypertensionChart)
);
}
or for simplifying
get isChart(): boolean {
return this.isTemperatureChart && this.isSomeOtherPropertyTrue
}
A long time, for me been obviously, that if I have complicated binary logic, and don't need for it any attributes from outside, I should use procedure. And just for clear code, all that times i try to use getters. But now i think, about a nature of this constructions, and can't find right answer. Is that ok, use getter just for GETTING, without associating it with some class property? Or is it not according to canons of OOP and getters/setters - only for encapsulation of class property?
Your 2nd example returning a primitive value is absolutely correct, but your 1st example will cause issues, because it will create a new Observable
every time that property is queried (and with it a subscription if you are using the async
pipe in your template). With angular, that would be every change detection cycle for that component, and for every time you query it inside your component ts.
In that case, you really should not use getters. If you want consumers to prevent overwriting the observable, and just read it, you should set the readonly
access modifier. That will change your example to:
readonly isChart$: Observable<boolean> = this.isTemperatureChart.pipe(
withLatestFrom(this.isHypertensionChart),
map(([isTemperature, isHypertension]) => isTemperature || isHypertension)
);
Not knowing your code, but judging by the naming of your variables, it feels like you are better of using combineLatest
instead of withLatestFrom