Skip to content

Instantly share code, notes, and snippets.

@praveen001
Created July 16, 2019 05:27
Show Gist options
  • Save praveen001/f5520b4a7d68f92d6ecea5a6548b110a to your computer and use it in GitHub Desktop.
Save praveen001/f5520b4a7d68f92d6ecea5a6548b110a to your computer and use it in GitHub Desktop.
Managing WebSocket with Redux Observable
let webSocketSubject: WebSocketSubject<{}>;
let onOpenSubject = new Subject();
let onCloseSubject = new Subject();
const connectSocket = websocketUrl => {
onOpenSubject = new Subject();
onCloseSubject = new Subject();
webSocketSubject = webSocket({
url: websocketUrl,
openObserver: onOpenSubject,
closeObserver: onCloseSubject
});
return webSocketSubject;
};
const connectEpic = (action$, state$: StateObservable<IState>) =>
action$.ofType(WebsocketActionTypes.CONNECT).switchMap(action =>
connectSocket(state$.value.config.socketUrl)
.catch(e =>
of(connectToWebSocket(state$.value.config.socketUrl))
.delay(5000)
.startWith(disconnectFromWebSocket())
)
.map(data => receiveMessageFromWebSocket(data))
);
const connectedEpic = action$ =>
action$.ofType(WebsocketActionTypes.CONNECT).switchMap(() =>
onOpenSubject.mergeMap(() => {
onCloseSubject.map(() => disconnectFromWebSocket());
return [
connectedToWebSocket(),
log('Websocket connected', LogLevel.INFO, {})
];
})
);
const connectedEpic2 = (action$, state$: StateObservable<IState>) =>
action$.ofType(WebsocketActionTypes.CONNECTED).switchMap(() =>
onCloseSubject.switchMap(e =>
of(connectToWebSocket(state$.value.event.config.socketUrl))
.delay(5000)
.startWith(disconnectFromWebSocket())
.startWith(log('Websocket disconnected', LogLevel.ERROR, e))
)
);
const disconnectEpic = action$ =>
action$.ofType(WebsocketActionTypes.DISCONNECT).map(() => {
webSocketSubject.complete();
return disconnected();
});
const sendMessageEpic = action$ =>
action$.ofType(WebsocketActionTypes.SEND_MESSAGE).map(action => {
webSocketSubject.next(action.payload);
// console.log('Socket message sent at time: ', Date.now());
return sentMessage();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment