简体   繁体   中英

ionic 2 / rxjs5 / cordova network plugin event observable

is it somehow possible to make an rxjs observable with the fromEvent method out of the cordova network connection plugin .

i am trying that with ionic 2.

i can see, that there are two events (online/offline) in the cordova network connection plugin . but how to hook into them with rxjs?

something that looks like that:

const offline$ = Observable.fromEvent(CORDOVA_OFFLINE_EVENT);
offline$.subscribe(
    function (connectionType) {
        console.log("connectionType", JSON.stringify(connectionType));
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    }
);

You can do it normally like the documentation says ( document.addEventListener("offline", onOffline, false); ), and in the handler you can emit with an EventEmitter or if you still want to use observable you can dispatch custom event to the document and make Observable.fromEvent(document, 'nameofevent')

Example:

window.addEventListener('offline', this.onOffline);
onOffline(e) {
        var event = new CustomEvent('onoffline');
        event['offlineTimestamp'] = new Date()
        document.dispatchEvent(event);
    }

and than just this.networkObservable = Observable.fromEvent(document, 'onoffline');

or instead of dispatching CustomEvent, you can have an EventEmitter which will emit in the handlers

networkEmitter = new EventEmitter();
window.addEventListener('offline', onOffline);
    onOffline(e) {
            this.networkEmitter.emit('wentOffline');
        }

You can than subscribe in the EventEmitter or Observable :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM