title: RxJs: how to maintain one WebSocket connection across multiple components?
body: <p>I have a chat application that consists of multiple components (e.g. one components holds a group list, another one contains messages, etc.), and when one component is opened another one must be closed.</p>
  <p>So here is a service that I'm using to provide a webSocket connection:</p>
  <pre><code>@Injectable()
  export class ChatConnectionService {
  
    private _connection: Subject&lt;any&gt;;
  
    constructor(private window: WindowAbstract) { }
  
    public closeConnection(): void {
      this.connection.complete();
    }
  
    public send(msg: ChatRequest): void {
      this.connection.next(msg);
    }
  
    public messages(): Subject&lt;any&gt; {
      return this.connection;
    }
  
    private get connection(): Subject&lt;any&gt; {
      if (!this._connection || this._connection.closed) {
        this._connection = webSocket(`https/myapp/chat`);
      }
  
      return this._connection;
    }
  }
  </code></pre>
  <p>And here is a usage example in <code>some.component.ts</code>:</p>
  <pre><code>  private messages$: Subscription;
  
    ngOnInit(): void {
      this.messages$ = this.chatConnectionService.messages()
        .subscribe(m =&gt; this.handleInboundMessage(m));
    }
  
    ngOnDestroy() {
      this.messages$.unsubscribe();
    }
  </code></pre>
  <p>Now the problem is that when I switch between components, once it gets unsubscribed when an old component being destroyed, a new subscription does not seem to be working, it does not send or received messages and does not produce any error as well.</p>
  <p>But when I remove unsubscribe line it starts working, but keeps receiving messages using the old subscription as well, which is not what I really want.</p>
  <p>So summarizing it all - I need to maintain one connection but having a possibility for multiple components to subscribe and unsubscribe as needed, is it possible to accomplish it with RxJs? Or what am I doing wrong? Any suggestion will be appreciated, thanks!</p>