Created
July 16, 2019 05:27
-
-
Save praveen001/f5520b4a7d68f92d6ecea5a6548b110a to your computer and use it in GitHub Desktop.
Managing WebSocket with Redux Observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
) | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const disconnectEpic = action$ => | |
action$.ofType(WebsocketActionTypes.DISCONNECT).map(() => { | |
webSocketSubject.complete(); | |
return disconnected(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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