使用共享的 RxJS observable 重新连接 WebSocket [英] Reconnecting a WebSocket with a shared RxJS observable

查看:57
本文介绍了使用共享的 RxJS observable 重新连接 WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的可观察对象:

I have an observable like this:

const records$ =
    Rx.DOM.fromWebSocket('ws://192.168.2.4:9001/feed/', null)
    .map(ev => parseRecord(ev.data))
    .share();

我有很多订阅者.当连接丢失时,所有订阅者都取消订阅:

I have many subscribers. When the connection is lost, all subscribers unsubscribe:

let records$Subscription;
records$Subscription = records$.subscribe(
    record => { ... },
    error => records$Subscription.dispose()
);

我验证了对 dispose 的调用确实对每个订阅进行了一次.因此,share 引用计数已达到零.

I verified that the call to dispose is indeed being made once for every subscription. Therefore, the share refcount has reached zero.

然而,当我现在再次订阅 records$ 时,没有建立新的 WebSocket 连接.但是,当我删除对 share 的调用时,它.为什么 share 不能按预期工作?

However, when I now subscribe to records$ again, no new WebSocket connection is set up. When I remove the call to share, however, it is. How come this doesn't work as expected with share?

推荐答案

我相信 rxjs v5,share 确实允许您重新连接,但在 Rxjs v4 中不允许.

I believe in rxjs v5, share does allow you to reconnect but not in Rxjs v4.

在 Rxjs 4 中,share 基本上是 multicast.refCount 并且一旦用于多播的主题完成,就不能重用(根据 Rxjs 语法规则,有一个看不同RxJS主题的​​语义是什么? 也是),导致您观察到的行为.

In Rxjs 4, share is bascially multicast.refCount and once the subject used for the multicast is completed, it cannot be reused (per Rxjs grammar rules, have a look at What are the semantics of different RxJS subjects? too), leading to the behaviour you observed.

在 Rxjs 5 中,它使用主题工厂(类似于 multicast(() => new Rx.Suject().refCount())),因此在必要时会重新创建主题.

In Rxjs 5, it uses a subject factory (something like multicast(() => new Rx.Suject().refCount())), so a subject is recreated when necessary.

查看问题此处此处了解更多详情.

See issues here and here for more details.

简而言之,如果您无法处理当前的行为,则可以切换到 v5(请注意,它仍处于测试阶段,并且有一些重大更改).

In short, if you can't do with the current behavior, you can switch to the v5 (note that it is still in beta and there are some breaking changes).

这篇关于使用共享的 RxJS observable 重新连接 WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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