是否可以返回新的可观察内部运算符,嵌套的observable

时间:2015-12-03 14:34:30

标签: javascript rxjs

var url = "http://domain.com/some/url";
// this endpoint will return websocket URL

Rx.DOM.ajax({
  url: url,
  method: 'GET',
  responseType: 'json'
}).scan(function(o, data) {
  // data.websocker is websocker url
  return Rx.DOM.fromWebSocket(data.websocket_url, null, function(o) {
    console.log(o);
  }, function(o) {
    console.log(o);
  });
}).subscribe(function(data) {
  // Success Message
  console.log(data);
}, function(error) {
  // Log the error
  console.log(error);
});

如上例所示。是否有可能从promises这样的运算符内发送Observable?

1 个答案:

答案 0 :(得分:0)

当然这很常见,并且存在很多运算符以各种方式处理内部可观察量。在此示例中,您可以使用flatMap代替scan

var url = "http://domain.com/some/url";
// this endpoint will return websocket URL

Rx.DOM.ajax({
  url: url,
  method: 'GET',
  responseType: 'json'
}).flatMap(function (data) {
  // data.websocker is websocker url
  return Rx.DOM.fromWebSocket(data.websocket_url, null, function(o) {
    console.log(o);
  }, function(o) {
    console.log(o);
  });
}).subscribe(function(data) {
  // will receive messages that are received from the websocket
  console.log(data);
}, function(error) {
  // Log the error
  console.log(error);
});