问题
I am expanding upon ping-pong example of redux-observable, and my final goal is to dispatch an action upon each received event from server.
But i am having a bit of trouble wrapping my head around how to actually achieve this.
What i have so far:
1.Upon opening a connection my server starts sending messages.
// server.js
setInterval(()=>{
ws.send(JSON.stringify({
type: 'INCREMENT',
status: 200
}))
console.log("sent some data")
},3000)
2. On the client i have established an Observable of that Websocket connection.
const socket$ = Observable.webSocket("ws://localhost:8081")
The rest of the code is similar to the JSBin Example for react
How do i form an epic for this task? How do i dispatch an action?
回答1:
We discussed a bit in the comments, but I'm afraid I'm still not entirely clear on how the increment/counter/INCREMENT_APPLY relates to the socket, but I can get you a simple example:
const somethingEpic = action$ =>
action$.ofType('START_SOCKET_OR_WHATEVER')
.switchMap(action =>
Observable.webSocket('ws://localhost:8081')
.map(response => ({ type: 'RECEIVED_MESSAGE', paylod: response }))
);
Here when START_SOCKET_OR_WHATEVER
is dispatched, we'll start listening to our socket. Whenever a message is received we map it into a RECEIVED_MESSAGE
action which will be dispatched after when epic emits it.
You'll notice this is nearly identical to how you would do a single ajax too. It only would be become notably different if you need to send messages to the server or multiplex.
来源:https://stackoverflow.com/questions/45638295/subscribe-to-a-stream-of-events-from-server