How to avoid race conditions when subscribing to observables in Angular

506 views Asked by At

I'm new to Angular and was writing this code.

  onUpdate(relation: RelationTypes) {
    let userId: number;
    this.assigneeId$.subscribe(assigneeId => userId = assigneeId);

    let customerId: string;
    this.customer$.subscribe(customer => customerId = customer.email);

    this.store.dispatch(actions.changeUserRelation({
      payload: {
        'userId': userId,
        'customerId': customerId,
        'relation': relation
      }
    }));
  }

The customerId$ and assigneeId$ are observables. I know that there might be the chance of a race condition here, which I would love to eliminate.

So I was thinking of something like this.


     this.subscription.add(this.assigneeId$.subscribe(assigneeId => {
       this.customer$.subscribe(customer => {
         this.store.dispatch(actions.changeUserRelation({
           payload: {
             'userId': assigneeId,
             'customerId': customer.email,
             'relation': relation
           }
         }));
       });
     }));

But this isn't working. Maybe I you can help me understand and fix the problem. Thanks in advance.

1

There are 1 answers

0
Felix On

RxJS offer different operators to combine observables. I think in this case you can use combineLatest, like this:

combineLatest([this.assigneeId$, this.customer$]).subscribe(([assigneeId, customer]) => 
    this.store.dispatch(actions.changeUserRelation({
       payload: {
         'userId': assigneeId,
         'customerId': customer.email,
         'relation': relation
       }
    }));
);