对流redux的重复操作可观察到

时间:2018-11-25 13:11:03

标签: socket.io redux-observable

订阅套接字io事件时,会触发重复的动作。

const onStartGameActionEpic = (action$, state$) => action$.pipe( ofType(ON_START_GAME), mergeMap(() => fromEvent(socket, 'newGameCreated').pipe( map(response => onStartGameFulfilled(response)), ), ), );

1 个答案:

答案 0 :(得分:0)

每次ON_START_GAME出现时,您都在创建一个新的侦听器,但是您绝不会杀死旧的侦听器。这是问题的根源。

修复1

mergeMap更改为switchMap

修复2

您可能希望一次玩多个游戏。如果是这样,请为您的namespace动作分配一个ON_START_GAME道具。当游戏结束动作触发时,杀死该特定的可观察对象。

const onStartGameActionEpic = (action$, state$) =>
    action$.pipe(
        ofType(ON_START_GAME),
        mergeMap(onStartGameAction =>
            fromEvent(socket, 'newGameCreated').pipe(
                takeUntil(action$.pipe(
                    ofType(ON_END_GAME),
                    filter(onEndGameAction => (
                        endGameAction.namespace === startGameAction.namespace
                    )),
                )),
                map(response => onStartGameFulfilled(response)),
            ),
        ),
    );