1

当用作带有事件的可观察对象的管道时,运算符document.visibilityState返回的值与预期不同。mapTo()document.visibilitychange

fromEvent(document, 'visibilitychange')
  .pipe(
    mapTo(document.visibilityState)
  )
  .subscribe((val) => {
    console.log(val, document.visibilityState);
  });

笔示例:https ://codepen.io/nametoforget/pen/ZEQmdBj

请参阅控制台登录笔。

4

1 回答 1

1

mapTo在开始时捕获一次返回值并一直使用此初始值。如果您想使用最新的值,请map改为:

const { fromEvent } = rxjs; // = require("rxjs")
const { map, startWith } = rxjs.operators; // = require("rxjs/operators")

fromEvent(document, 'visibilitychange')
  .pipe(
    map(() => document.visibilityState),
    startWith(document.visibilityState)
  )
  .subscribe((val) => {
    console.log(val, document.visibilityState);
  });
<script src="https://unpkg.com/rxjs@6.6.0/bundles/rxjs.umd.min.js"></script>

于 2020-07-19T22:30:22.940 回答