Reconnecting a WebSocket with a shared RxJS observable

我们两清 提交于 2019-12-12 02:50:58

问题


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

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

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?


回答1:


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

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.

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.

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).



来源:https://stackoverflow.com/questions/36675104/reconnecting-a-websocket-with-a-shared-rxjs-observable

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