document.visibilityState 值与 mapTo() 运算符的预期不符

document.visibilityState value not as expected with mapTo() operator

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

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

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

查看控制台登录笔。

mapTo 在开始时捕获一次 return 值并一直使用这个初始值。如果您想获得最新值,请改用 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>