Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save typelogic/0ef19d6723e511a9ee32fa2afa553ae8 to your computer and use it in GitHub Desktop.
Save typelogic/0ef19d6723e511a9ee32fa2afa553ae8 to your computer and use it in GitHub Desktop.
[React Native + RxJS] Create an Observable from DeviceEventEmitter - An example to handle 'locationUpdated' event
import React, {DeviceEventEmitter} from 'react-native';
import {Observable} from 'rx-lite'
/**
* Creates an Observable to listen to any event of DeviceEventEmitter
* @param type {string} Event type
*/
export default createObservableFromDeviceEventEmitter$ = type => {
let subscription;
return Observable.fromEventPattern(
handler => subscription = DeviceEventEmitter.addListener(type, handler),
handler => subscription.remove()
)
}
import createObservableFromDeviceEventEmitter$ from './createObservableFromDeviceEventEmitter';
/**
* Creates an Observable to listen to `locationUpdated` event
* dispatched by Location (react-native-location)
*/
export default locationDidUpdate$ = (delay=1000) => {
return createObservableFromDeviceEventEmitter$('locationUpdated')
.throttle(delay) // delay of listening to events
.map((location) => {
// map latitude + longitude into simple object
return {
latitude: location.coords.latitude,
longitude: location.coords.longitude
}
});
}
import Location from 'react-native-location';
import locationDidUpdate$ from './locationDidUpdate';
// init native location
Location.requestAlwaysAuthorization();
Location.startUpdatingLocation();
// subscribe to changes
const subscription = locationDidUpdate$(2000/* delay ms */)
.subscribe(
(location) => {
// do anything with the location
console.log('location updated', location)
},
(e) => console.log('onError: %s', e);
);
// to unsubscribe just call
// subscription.dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment