rxjsvisibilitychange

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


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.


Solution

  • 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/rxjs@6.6.0/bundles/rxjs.umd.min.js"></script>