Forked from sectore/01-createObservableFromDeviceEventEmitter.js
Created
May 23, 2018 11:59
-
-
Save orette/12b321411d2d48a44b09acd3a351a372 to your computer and use it in GitHub Desktop.
[React Native + RxJS] Create an Observable from DeviceEventEmitter - An example to handle 'locationUpdated' event
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| ) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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