RxJs Observable with WebSocket

前端 未结 4 940
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 14:01

My angular application uses a websocket to communicate with the backend.

In my test case I have 2 client components. The Observable timer prints two different clie

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 14:49

    You need to use the share operator to share it among the subscribers.

    this.observable = Observable.create(
        (observer: Observer) => {
           socket.onmessage = observer.next.bind(observer);
           socket.onerror = observer.error.bind(observer);
           socket.onclose = observer.complete.bind(observer);
           return socket.close.bind(socket);
        }
    ).share();
    

    Also make sure this service is a singleton.

    Doc: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/share.md

提交回复
热议问题