title: RxJs Observable with WebSocket
body: <p>My angular application uses a websocket to communicate with the backend.</p>
  
  <p>In my test case I have 2 client components. The Observable timer prints two different client id's as expected.</p>
  
  <p>Each ngOnInit() also prints the id of its client.</p>
  
  <p>NOW for some reason, the subscription of websocketService.observeClient() is called 2 times for each message but <code>this.client.id</code> always prints the value of the second client.</p>
  
  <p>Heres my client component</p>
  
  <pre class="lang-js prettyprint-override"><code>@Component({
  ...
  })
  export class ClientComponent implements OnInit {
  
    @Input() client: Client;
  
    constructor(public websocketService: WebsocketService) {
      Observable.timer(1000, 1000).subscribe(() =&gt; console.log(this.client.id));
    }
  
    ngOnInit() {
  
      console.log(this.client.id);
      this.websocketService.observeClient().subscribe(data =&gt; {
        console.log('message', this.client.id);
      });
  
    }
  
  }
  </code></pre>
  
  <p>And my websocket Service</p>
  
  <pre class="lang-js prettyprint-override"><code>@Injectable()
  export class WebsocketService {
  
    private observable: Observable&lt;MessageEvent&gt;;
    private observer: Subject&lt;Message&gt;;
  
    constructor() {
  
      const socket = new WebSocket('ws://localhost:9091');
  
      this.observable = Observable.create(
        (observer: Observer&lt;MessageEvent&gt;) =&gt; {
          socket.onmessage = observer.next.bind(observer);
          socket.onerror = observer.error.bind(observer);
          socket.onclose = observer.complete.bind(observer);
          return socket.close.bind(socket);
        }
      );
  
      this.observer = Subject.create({
        next: (data: Message) =&gt; {
          if (socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify(data));
          }
        }
      });
  
    }
  
    observeClient(): Observable&lt;MessageEvent&gt; {
      return this.observable;
    }
  
  }
  </code></pre>
  
  <hr>
  
  <p>Edit</p>
  
  <p>Ok as far as I have read it has to do with the fact that Observables are unicast objects and I have to use a Subject for that but I don't know how to create the Subject.</p>