推迟观察

Defer Observables

我正在使用标准的 WebSocket,它发送消息并最终收到响应。以前,我使用 $q.defer,存储延迟对象并返回一个承诺。响应处理程序将查找存储的延迟对象并使用值解析它。

这是否可能使用 observables?

// As part of the websocket setup
websocket.onmessage = function(message) {
    uuid = message.someResponse.uuid;
    this._observables[uuid].create(function(observer) {
        observer.onNext(response);
        observer.onCompleted();
    });
}

public sendRequest(request : any) : Observable<any> {
    this.sendMessage(request);
    return this._observables[request[Object.keys(request)[0]].uuid] = new Observable();
}

// Inside some requesting method
var observable = this.sendRequest(request);
observable.subscribe(
    response => console.log(response),
    response => console.log(response.error),
    () => {
        delete this._callbacks[uuid];
    }
);

我会这样重构你的代码:

public initialize() : Observable<any> {
  return Observable.create(observer => {
    websocket.onmessage = function(message) {
      uuid = message.someResponse.uuid;
      observer.next(message);
    }
  });
}

以及发送和接收消息的方式:

var observable = initialize();

var request = (...)
this.sendRequest(request);

observable.subscribe(
  message => {
    // called each time a message is received
    console.log(message)
  },
  response => {
    console.log(response.error)
  },
  () => {
  }
);

与 promises 相反,observables 需要初始化一次,因为它们支持事件。每发送一条消息,都会以消息为参数调用事件回调(subscribe方法的第一个参数)。

有关详细信息,您可以在第 "Event-based support" 部分查看以下文章: