initStepCountObserver().md 2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
Setup an HKObserverQuery for step count (HKQuantityTypeIdentifierStepCount) that will
trigger an event listenable on react-native `NativeAppEventEmitter` when the
Healthkit step count has changed.

The `initStepCountObserver` method must be called before adding a listener to
NativeAppEventEmitter. After the step count observer has been initialized you can
listen to the NativeAppEventEmitter `change:steps` event and re-fetch relevent
step count data in the event handler.

The `initStepCountObserver` method should be called after Healthkit has been
successfully initialized (AppleHealthkit.initHealthKit has been called without
error).

```javascript
// import NativeAppEventEmitter from react-native
import {
  Navigator,
  View,
  NativeAppEventEmitter,
} from 'react-native';
```

```javascript
AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
  if (this._handleHKError(err, 'initHealthKit')) {
    return;
  }

  // initialize the step count observer
  AppleHealthKit.initStepCountObserver({}, () => {});

  // add event listener for 'change:steps' and handle the
  // event in the event handler function.
  //
  // when adding a listener, a 'subscription' object is
  // returned that must be used to remove the listener
  // when the component unmounts. The subscription object
  // must be accessible to any function/method/instance
  // that will be unsubscribing from the event.
  this.sub = NativeAppEventEmitter.addListener(
    'change:steps',
    (evt) => {
      // a 'change:steps' event has been received. step
      // count data should be re-fetched from Healthkit.
      this._fetchStepCountData();
    }
  );

  // other tasks to perform after Healthkit has been
  // initialized (fetch relevant Healthkit data).
  this._fetchStepCountData();
  this._fetchOtherRelevantHealthkitData();
  // ...
});

...

// when the component where the listener was added unmounts
// (or whenever the listener should be removed), call the
// 'remove' method of the subscription object.
componentWillUnmount() {
  this.sub.remove();
}
```