2

I have the following scenario.

If the users enter in the route with only /lobby without an ?competitionId= I must search on the state the favorite competition of the user. After receive the favorite competition of the user, i must redirect the user to /lobby?competitionId=XYZ.

I'm using the following code. Is a better way to implement ? It's looking like an callback hell to me. I'm using NGRX.

RxJS Stream Observsable Way

redirectToCompetition(): void {
this._store.pipe(select(routerSelectors.getState)).subscribe(routerState => {
  if (!routerState.queryParams.competitionId) {
    this._store
      .pipe(select(authenticatedUserSelectors.getFavoriteCompetition))
      .subscribe(favoriteCompetition => {
        this._store.dispatch(
          new routerActions.NavigateTo({
            path: ['/lobby'],
            query: { competitionId: favoriteCompetition.id }
          })
        );
      });
  }
});
}

I rewrite the code using async/await. It looks better.

Promise Async/Await Way

async redirectToCompetitionPromise() {
    const routerState = await this._store
      .pipe(select(routerSelectors.getState))
      .first()
      .toPromise();

    const userFavoriteCompetition = await this._store
      .pipe(select(authenticatedUserSelectors.getFavoriteCompetition))
      .first()
      .toPromise();

    if (!routerState.queryParams.competitionId) {
      this._store.dispatch(
        new routerActions.NavigateTo({
          path: ['/lobby'],
          query: { competitionId: userFavoriteCompetition.id }
        })
      );
    }
  }

Any problem to use RxJS with async/await pattern ? Or in my first code i'm doing an bad implementation ?

1 Answer 1

1

Nothing wrong with use async/await and promise with rxjs, just rxjs itself can handle it quite well already, if use right

this._store
.pipe(select(routerSelectors.getState))
.first()
.filter(routerState =>routerState.queryParams.competitionId)
.switchMap(()=>this._store.pipe(select(authenticatedUserSelectors.getFavoriteCompetition)))
.do(favoriteCompetition =>
        this._store.dispatch(
          new routerActions.NavigateTo({
            path: ['/lobby'],
            query: { 
            competitionId: favoriteCompetition.id }
          })
        );
      ).subscribe()
  

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. We can't put first(), filter(), switchMap() inside de pipe( ... ) ?
just my personal perference, don't like pipe too much myself. I don't see it save a lot of typing
Great. Just one thing is wrong is your implementation based in my use case. I edited your answer to fix to mark your answer as the correct. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.