首页 > 解决方案 > eventChannel 发射器动作不是取自 redux-saga

问题描述

我创建了 saga watcher 来连接 websocket 并监听接收到的数据。常量有效载荷 = 收益 take(socketChannel); 正在等待接收收到的消息,但并非全部来自

emit({type: 'WEBSOCKET_MESSAGE_RECEIVED', message});

有人可以帮助找到问题吗?

function createWebSocketConnection() {
    return new Promise((resolve) => {
        websocket.onOpen(() => {
            makeRequests(websocket);
            resolve(websocket);
        });

        websocket.connect(true);
    });
}


    function createSocketChannel(socket) {
        return eventChannel((emit) => {
            socket.onMessage((message) => {
                if (message.path) {
                    console.log('Emitting received data...');
                    return emit({type: 'WEBSOCKET_MESSAGE_RECEIVED', message});
                }
            });

            socket.onClose(() => {
                emit(END);
            });

            socket.onError(() => {
                emit(END);
            });

            const unsubscribe = () => {
                socket.onMessage = null;
            };

            return unsubscribe;
        });
    }

    function* listenForSocketMessages() {
        let socket;
        let socketChannel;

        try {
            socket = yield call(createWebSocketConnection);
            socketChannel = yield call(createSocketChannel, socket);

            // tell the application that we have a connection
            yield dispatch(ActionCreators.wsClientOpened());

            while (true) {
                // wait for a message from the channel
                const payload = yield take(socketChannel);
                console.log('new payload');
                // a message has been received, dispatch an action with the message payload
                yield dispatch(createAction(payload.path, payload));
            }
        }
        catch (error) {
            // yield dispatch(ActionCreators.wsClientError());
        }
        finally {
            if (yield cancelled()) {
                // close the channel
                socketChannel.close();

                // close the WebSocket connection
                socket.close();
            }
            else {
                // yield dispatch(ActionCreators.wsClientError());
            }
        }
    }

    const createAction = (type: string, payload?: any) => ({
        type,
        payload,
    });

    export default function* watchConnectWebsocket() {
        // starts the task in the background
        const socketTask = yield fork(listenForSocketMessages);

        // when DISCONNECT action is dispatched, we cancel the socket task
        yield take(WsActionTypes.WEBSOCKET_CLOSED);
        yield cancel(socketTask);
        yield dispatch(ActionCreators.wsClientClosed());
    }

标签: reactjswebsocketredux-saga

解决方案


推荐阅读