从服务器订阅事件流 [英] Subscribe to a stream of events from server

查看:50
本文介绍了从服务器订阅事件流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展 redux-observable 的 ping-pong 示例,我的最终目标是对来自服务器的每个接收到的事件分派一个动作.

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.打开连接后,我的服务器开始发送消息.

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.在客户端上,我已经建立了该 Websocket 连接的 Observable.

2. On the client i have established an Observable of that Websocket connection.

const socket$ = Observable.webSocket("ws://localhost:8081")

其余代码类似于 JSBin Example for react

我如何为这项任务形成史诗?我如何分派动作?

How do i form an epic for this task? How do i dispatch an action?

推荐答案

我们在评论中讨论了一些,但恐怕我仍然不完全清楚 increment/counter/INCREMENT_APPLY 与套接字的关系,但我可以给你举个简单的例子:

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 }))
    );

这里当 START_SOCKET_OR_WHATEVER 被调度时,我们将开始监听我们的套接字.每当收到消息时,我们将其映射到 RECEIVED_MESSAGE 操作,该操作将在史诗发出后分派.

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.

您会注意到这与您执行单个 ajax 的方式几乎相同.如果您需要向服务器或多路复用发送消息,它只会变得明显不同.

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.

这篇关于从服务器订阅事件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆