Search code examples
angularrxjsngrx

Observable or async/await for NGRX selectors?


I have an ngrx store and I'm calling the selector on ngOnInit (see below code). Somebody said that I should put this call in the async/await since I'm only waiting for one value. I am not sure if that is the right way because the observable calls its complete() function when the emit is done and since there's only one value it will immediately call complete(). Does anybody have a different opinion or a better approach? thank you.

ngOnInit(){
    this.store.pipe(select(selectSomeString), takeUntil(this.destroy$)).subscribe(
          (someString) => this.checkIfValid(someString)
        );
}

private checkIfValid(someString: string){
//some code
}

Solution

  • I am assuming that you are only using the first emitted value, since you mentioned on the question that you are only waiting for one value.

    In that case, I would recommend you to use the take operator after the select operator, and before the takeUntil operator.

    this.store.pipe(
      select(selectSomeString), 
      takeUntil(this.destroy$))
    .subscribe((someString) => 
      this.checkIfValid(someString)
    );
    

    Using take(1) will ensure that you take the 1st emitted value. You may read more about the operator here.