Skip to content

Instantly share code, notes, and snippets.

@sectore
Last active November 26, 2023 06:42
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save sectore/a8147ce68fc3966ce142 to your computer and use it in GitHub Desktop.
Save sectore/a8147ce68fc3966ce142 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