Rxjs: How to map to multiple actions so they are not processed in parallel

30 views Asked by At

I'm trying to implement card game with redux-observables. And what I'm trying to achieve to draw cards for each player but this needs to be done sequentialy. But they probably run concurently because content of deck is not changed after drawCards finished for previous player.

This is epic to deal cards:

export const dealCardsEpic = (action$: any, state$: any) => action$.pipe(
  filter(dealCards.match),
  mergeMap(() => {
    const players = selectPlayers(state$.value);

    return of(...players.inGame.flatMap((player, index) => {
      return drawCards({ playerId: player.id, count: index === 0 ? 5 : 4})
    }));
  })
);

And epic for draw cards:

export const drawFromDeckEpic = (action$: any, state$: any) => action$.pipe(
  filter(drawCards.match),
  concatMap((action: any) => {
    const cards = selectTopCards(state$.value, action.payload.count);
    
    return [
      addCardsToPlayer({playerId: action.payload.playerId, cards}),
      removeCards(action.payload.count),
      setNextPlayerTurn()
    ];
  }),
);

I do dispatch actions like this:

    dispatch(prepareDeck());
    dispatch(shuffleDeck());
    dispatch(addPlayer({
      id: '1',
      name: 'Petr',
      color: 'blue',
      inHand: []
    }));
    dispatch(clearHand('1'));
    dispatch(addPlayer({
      id: '2',
      name: 'Andrea',
      color: 'green',
      inHand: [],
    }));
    dispatch(clearHand('2'));
    dispatch(setPlayerTurn('1'));
    dispatch(dealCards());

I see actions dispatched in devtools:

  • deck/dealCards
  • deck/drawCards
  • deck/drawCards
  • players/addCardsToPlayer
  • deck/removeCards
  • players/setNextPlayersTurn
  • players/addCardsToPlayer
  • deck/removeCards

Any tips would be much appriciated. Thanks in advance.

0

There are 0 answers