Subscribe to a stream of events from server

有些话、适合烂在心里 提交于 2019-12-24 11:14:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!