Search code examples
angulartypescriptrxjsngrx

TypeScript: Assign new Observable to initialized Observable variable


Just to check if there are no hidden catches in this one.

Imagine a situation with a component with @Input() setter function, where the private variable is set together with an NgRx selector assigned to another variable:

private _inputValue: SomeDto;
asyncProperty$: Observable<boolean>;

@Input() set someValue(inputValue: SomeDto) {
  this._inputValue = inputValue
  this.asyncProperty$ = this.store.select(fromStore.selectSomeValue());
  // and some other logic...
}

In HTML:

<div *ngIf="asyncProperty$ | async" class="testClass">...</div>

Is it safe to assign new Observable to asyncProperty$ variable each time the component input changes? I have a strange feeling I should rather avoid this approach but can't tell why.


Solution

  • To elaborate on martin's comment, Angular's change detection will trigger when the @Input value changes. During the component's life-cycle Angular will unsubscribe from Observables passed to the async pipe, and in this case, subscribe to the new one that has been pass to async.