我试图在我的React-Redux应用程序中建立按需的wensocket连接。 RxJS提供了webscoketSubject用于管理webscoket。收到动作后,我想使用webscoketSubject启动连接,对于随后的启动webscokets请求,如果已经建立连接,我将重用套接字。但是,当我这样做时,会在我保存在内存中的webscoketSubject参考中创建一个新的订阅,并且由于每当收到来自Server的消息时,都会得到重复的操作。
这是代码段。
import { ofType } from 'redux-observable';
import { delay, mapTo, switchMap, mergeMap, map, skipUntil, skipWhile, takeUntil, catchError, take } from 'rxjs/operators';
import { Observable, DataEvent, WebSocket, of } from 'rxjs';
import { WebSocketSubject } from 'rxjs/webSocket';
let socket;
const getWebSocket = () => {
console.log("socket", socket);
if(socket) {
console.log(socket.closed);
}
if(!socket) {
console.log("creating new socket");
socket = new WebSocketSubject("ws://localhost:9091/web-socket");
}
return socket;
}
//maps a websocket recieved message to redux store types
const websocketMsgMapper = payload => {
return {
type : 'WORKFLOWS_RECEIVED',
workflows : payload.workflows
}
};
export const openSocketEpic = action$ => action$.pipe(
ofType('START_WEBSOCKET'),
mergeMap( action => {
const socket$ = getWebSocket();
console.log(socket$);
return socket$.pipe(
map(websocketMsgMapper),
takeUntil(action$.pipe(ofType('STOP_WEBSOCKET'))),
catchError(error => of({
type : 'WORKFLOWS_RECEIVED_ERROR'
}))
);
})
);