0

如下图,为什么示例1在我们返回div然后单独返回一个新的click observable flatMap to 时会失败click$

示例 2 工作正常。JSBin 下面试试看

任何人都可以解释为什么会发生这种情况?据我了解,flatMap 扩展了 Observable。 http://jsbin.com/sowodi/3/edit?js,控制台,输出

// Example 1
() => {
  let stream = Rx.Observable.fromArray([1, 2, 3]);

  let div$ = stream.map(i => {
    let div = document.createElement('div');
    div.innerHTML = `NOT WORKING DIV ${i}`;
    return div;
  })

  div$.subscribe(div => {
    document.querySelector('body').appendChild(div);
  })

  let click$ = div$.flatMap(
    div => Rx.Observable.fromEvent(div, 'click')
  );

  click$.subscribe(click => console.log('click'));
}();


// Example 2
() => {
  let stream = Rx.Observable.fromArray([4, 5, 6]);

  let click$ = stream.flatMap(i => {
    let div = document.createElement('div');
    div.innerHTML = `DIV ${i}`;
    document.querySelector('body').appendChild(div);

    return Rx.Observable.fromEvent(div, 'click');
  })

  click$.subscribe(click => console.log('click'));
}();
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <div id="app">
    THE APP ID
  </div>
</body>

</html>

4

1 回答 1

0

这是因为在您的第一个示例中,您正在创建两组 div。您已经完成了与此等效的操作:

  Rx.Observable.fromArray([1, 2, 3])
    .map(i => {
      let div = document.createElement('div');
      div.innerHTML = `NOT WORKING DIV ${i}`;
      return div;
    }).subscribe(div => {
      document.querySelector('body').appendChild(div);
    })

  Rx.Observable.fromArray([1, 2, 3])
    .map(i => {
      let div = document.createElement('div');
      div.innerHTML = `NOT WORKING DIV ${i}`;
      return div;
  }).flatMap(
      div => Rx.Observable.fromEvent(div, 'click')
  ).subscribe(click => console.log('click'));

至于为什么,这是因为fromArray创建了一个Observable的含义,即每个订阅都会创建一个全新的独立,这不会影响您创建的任何其他流。

有两种方法可以修复它,1)您已经发现只创建一个流来容纳所有逻辑,或者 2)或者,您可以将 div$ 的结果设为热Observable,以便所有订阅实际上共享同一个流。这将带来一系列问题,即如果您不小心,您现在可能会错过消息,但要重构您的第一个案例,它最终会看起来像:

  let stream = Rx.Observable.fromArray([1, 2, 3]);

  let div$ = stream.map(i => {
    let div = document.createElement('div');
    div.innerHTML = `NOT WORKING DIV ${i}`;
    return div;
  })
  //Make div$ into a connectable Observable so the subscriptions will
  //share the underlying Observable
  .publish()

  div$.subscribe(div => {
    document.querySelector('body').appendChild(div);
  })

  let click$ = div$.flatMap(
    div => Rx.Observable.fromEvent(div, 'click')
  );

  click$.subscribe(click => console.log('click'));

  //Nothing happens until you call connect which subscribes to the underlying
  //Observable
  div$.connect();
于 2016-02-05T08:14:15.063 回答