user1804599
user1804599

Reputation:

Reconnecting a WebSocket with a shared RxJS observable

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?

Upvotes: 0

Views: 1511

Answers (1)

user3743222
user3743222

Reputation: 18665

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

Upvotes: 1

Related Questions