Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CombineLatest first event not firing

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

like image 579
Dieterg Avatar asked Nov 29 '17 10:11

Dieterg


People also ask

What is an example of a combinelatest event?

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.

What happens if combinelatest does not complete?

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.

What happens when multiple observables are passed to combinelatest?

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.

How do I fix the “combinelatest” operator when combining streams?

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.


1 Answers

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.

like image 148
martin Avatar answered Oct 17 '22 15:10

martin