11

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: ....

Dieterg
  • 16,118
  • 3
  • 30
  • 49

1 Answers1

34

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.

martin
  • 93,354
  • 25
  • 191
  • 226