title: Websocket in Angular 4 and RxJS confusion
body: <p>I am trying to learn RxJS with websockets and Angular 4, and found a good example <a href="https://tutorialedge.net/post/typescript/angular/angular-websockets-tutorial/" rel="noreferrer">here</a>.  I'm hoping someone can help explain the example as a few things are confusing.</p>
  
  <p>They have created 2 Angular services, the Websocket Service:</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import * as Rx from 'rxjs/Rx';
  
  @Injectable()
  export class WebsocketService {
    constructor() { }
  
    private subject: Rx.Subject&lt;MessageEvent&gt;;
  
    public connect(url): Rx.Subject&lt;MessageEvent&gt; {
      if (!this.subject) {
        this.subject = this.create(url);
        console.log("Successfully connected: " + url);
      } 
      return this.subject;
    }
  
    private create(url): Rx.Subject&lt;MessageEvent&gt; {
      let ws = new WebSocket(url);
  
      let observable = Rx.Observable.create(
      (obs: Rx.Observer&lt;MessageEvent&gt;) =&gt; {
          ws.onmessage = obs.next.bind(obs);
          ws.onerror = obs.error.bind(obs);
          ws.onclose = obs.complete.bind(obs);
          return ws.close.bind(ws);
      })
  let observer = {
          next: (data: Object) =&gt; {
              if (ws.readyState === WebSocket.OPEN) {
                  ws.send(JSON.stringify(data));
              }
          }
      }
      return Rx.Subject.create(observer, observable);
    }
  
  }
  </code></pre>
  
  <p>and the Chat service:</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { Observable, Subject } from 'rxjs/Rx';
  import { WebsocketService } from './websocket.service';
  
  const CHAT_URL = 'ws://echo.websocket.org/';
  
  export interface Message {
      author: string,
      message: string
  }
  
  @Injectable()
  export class ChatService {
      public messages: Subject&lt;Message&gt;;
  
      constructor(wsService: WebsocketService) {
          this.messages = &lt;Subject&lt;Message&gt;&gt;wsService
              .connect(CHAT_URL)
              .map((response: MessageEvent): Message =&gt; {
                  let data = JSON.parse(response.data);
                  return {
                      author: data.author,
                      message: data.message
                  }
              });
      }
  }
  </code></pre>
  
  <p>I've got a number of questions about this:</p>
  
  <ol>
  <li>Why is it necessary to create 2 services?  Can't a Subject be an observer and observable (so it could just relay the messages directly without a second Chat service)?  What problem does is solve creating 2 services?</li>
  <li>In the Websocket Service, why does the last line of the .create function call return ws.close.bind(ws)?  What does that do?</li>
  <li>How is a disconnect of the websocket handled?  Is there a way to make it reconnect?</li>
  <li>How should the services close/dispose of the websocket?</li>
  </ol>