Skip to content

Instantly share code, notes, and snippets.

@ezequieltejada
Forked from ccnokes/rx-online-offline.js
Created October 11, 2022 14:18
Show Gist options
  • Save ezequieltejada/b1f62e21c02562c076009954898acd3c to your computer and use it in GitHub Desktop.
Save ezequieltejada/b1f62e21c02562c076009954898acd3c to your computer and use it in GitHub Desktop.
Online/offline event observable with RxJS (see comments below for a better, more up-to-date way of doing this)
const { Observable } = require('rxjs/Observable');
require('rxjs/add/observable/fromEvent');
require('rxjs/add/operator/map');
require('rxjs/add/observable/merge');
function createOnline$() {
//merge several events into one
return Observable.merge(
//use .map() to transform the returned Event type into a true/false value
Observable.fromEvent(window, 'offline').map(() => false),
Observable.fromEvent(window, 'online').map(() => true),
//start the stream with the current online status
Observable.create(sub => {
sub.next(navigator.onLine);
sub.complete(); //this one only emits once, so now we end it
})
);
}
// implement it
const onlineSub = createOnline$().subscribe(isOnline => console.log(isOnline));
onlineSub.unsubscribe();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment