RxJS Challenge #02: Creating a page visibility stream
Yesterday we have been solving the first RxJS Challenge by Alex Inkin. And today is my turn!
The challenge is to write a page visibility RxJS stream and log in console when it emits. And there is also an additional interesting task for Angular developers: make a solution a global Injection Token.
Here you can try to solve it yourself first.
Let’s write a stream
First of all, let’s visit Page Visibility API docs on MDN. Now we see that there are visibilitychange
event and visibilityState
field on Document
.
Let’s organize it into one RxJS stream:
So, we use fromEvent
that listens to visibilitychange
event. After each change, the pipe transforms the stream to boolean
answering a question: Is visibilityState
not hidden?
It is also possible to use
document.hidden
field andvisibilityState === 'visible'
comparison. But the first one is deprecated and the second one will exclude stages prerender and unloaded that can be also…