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

430 Views Asked by At

The value of document.visibilityState returned by the mapTo() operator when used as a pipe with an observable of the document.visibilitychange event is not as expected.

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

Example pen: https://codepen.io/nametoforget/pen/ZEQmdBj

See console log in pen.

1

There are 1 best solutions below

0
Oles Savluk On BEST ANSWER

mapTo captures return value once at the beginning and use this initial value all the time. If you want to have most recent value use map instead:

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/[email protected]/bundles/rxjs.umd.min.js"></script>