第一个事件未触发

第一个事件未触发

本文介绍了CombineLatest 第一个事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我的应用程序何时脱机并重新联机.我在 rxjs 中注册了以下事件:

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'));
});

但是,当我第一次离线时,即使我添加常规的 addEventListener 事件,我也不会触发该事件,但我看到它们被很好地触发了:

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'));

这个jsbin为例,通过devtools和您将在第一次看到它不会登录 我在线:....

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

推荐答案

combineLatest 操作符要求所有源 Observable 至少发出一个值.

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)

如果你想知道navigator.onLine的初始状态,也许你甚至不需要使用skip(1).

Maybe you don't even need to use the skip(1) if you want to know the initial state of navigator.onLine.

这篇关于CombineLatest 第一个事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:34