I want to know when my application goes offline and comes back online. I have the following events registered in rxjs
:
const online = Rx.Observable.fromEvent(window, 'online');
const offline = Rx.Observable.fromEvent(window, 'offline');
const source = Rx.Observable.combineLatest(online, offline).map(() => navigator.onLine);
source.subscribe(result => {
console.log('I\'m online: ' + (result ? 'jup' : 'nope'));
});
But, the first time I go offline the event isn't triggered allthough if I add the regular addEventListener
events I see they're getting triggered fine:
window.addEventListener('online', () => console.log('online triggered'));
window.addEventListener('offline', () => console.log('offline triggered'));
Take a look at this jsbin as example, switch of your netwerk via devtools and you'll see the first time it won't log I'm online: ...
.
Basic examples of this can be seen in example three, where events from multiple buttons are being combined to produce a count of each and an overall total, or a calculation of BMI from the RxJS documentation. Be aware that combineLatest will not emit an initial value until each observable emits at least one value.
Also, if some input Observable does not emit any value and never completes, combineLatest will also never emit and never complete, since, again, it will wait for all streams to emit some value.
If at least one Observable was passed to combineLatest and all passed Observables emitted something, the resulting Observable will complete when all combined streams complete. So even if some Observable completes, the result of combineLatest will still emit values when other Observables do.
When combining streams with the combineLatest operator, where the source streams might have new values within the same call stack, you might get unexpected behavior. You can fix this by adding a debounceTime (0) right after the combineLatest.
The combineLatest
operator requires all source Observables to emit at least one value.
For you this means you should initialize each stream and then just listen to changes:
const source = Rx.Observable.combineLatest(
online.startWith(null),
offline.startWith(null),
)
.skip(1)
.map(() => navigator.onLine)
Maybe you don't even need to use the skip(1)
if you want to know the initial state of navigator.onLine
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With