RxJS dispose resource when no subscribers, create when new subscribers

ovg Source

I want to create and keep a single socket while I have subscribers, disconnect when I no longer have subscribers and reconnect when subscribers return.

This is what I have so far but when a subscriber unsubscribes the socket is disconnected for everyone.

  constructor() {
    this.socket = io(this.URL)
  }

  public getValue(): Observable<string> {
    let observable = new Observable<string>(observer => {
      this.socket.on('value', (data) => {
        let v = data['value'];
        observer.next(v)
      })

      return () => {
        this.socket.disconnect()
      }
    })

    return observable
  }
javascriptsocket.iorxjs

Answers

answered 3 months ago martin #1

This isn't doing exactly what you want because you're creating a new Observable every time you call getValue(). For example when you call getValue() twice and subscribe to both of them you'll have two different Observables. Then if you unsubscribe from any of them you'll close the socket connection for every Observable that was using it.

So a better way is to keep the Observable as a separate variable chained with the share() operator that will keep always only one subscription to its source Observable and will unsubscribe from it when all observers unsubscribe.

private socket$: Observable<string> = new Observable<string>(
  observer => {
    this.socket.on('value', (data) => {
      let v = data['value'];
      observer.next(v);
    });

    return () => this.socket.disconnect();
  })
  .share();

public getValue(): Observable<string> {
  return this.socket$;
}

comments powered by Disqus