Skip to content

Commit

Permalink
Merge pull request #195 from openmsupply/#194-tablet-battery-level
Browse files Browse the repository at this point in the history
Add different battery level listening implementation
  • Loading branch information
josh-griffin authored Jun 27, 2021
2 parents 22d1fed + 70c3386 commit c3b7e07
Showing 1 changed file with 49 additions and 3 deletions.
52 changes: 49 additions & 3 deletions src/ui/hooks/usePowerState.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useReducer } from 'react';
import { MILLISECONDS } from '~constants/Milliseconds';
import { useEffect, useReducer, useRef } from 'react';
import * as ExpoBattery from 'expo-battery';

/**
Expand Down Expand Up @@ -105,7 +106,52 @@ const reducer = (state = initialState(), action: PowerStateAction): PowerStateSh
}
};

type BatteryLevel = number;

type BatteryLevelListener = (batteryLevel: BatteryLevel) => void;

class BatteryLevelSubject {
listeners: Record<number, BatteryLevelListener>;

intervalHandler: NodeJS.Timeout;

currentId: number;

constructor() {
this.start();
this.currentId = 0;
this.listeners = {};
}

addListener(listener: BatteryLevelListener) {
const id = this.currentId;
this.listeners[id] = listener;
this.currentId += 1;

const remove = () => {
delete this.listeners[id];
};

return remove;
}

start() {
this.intervalHandler = setInterval(() => {
ExpoBattery.getBatteryLevelAsync().then(batteryLevel => {
Object.values(this.listeners).forEach(listener => {
listener(batteryLevel);
});
});
}, MILLISECONDS.TEN_SECONDS);
}

stop() {
clearInterval(this.intervalHandler);
}
}

export const usePowerState = (): PowerStateShape => {
const batterLevelSubject = useRef(new BatteryLevelSubject());
const [powerState, dispatch] = useReducer(reducer, initialState());

useEffect(() => {
Expand All @@ -124,7 +170,7 @@ export const usePowerState = (): PowerStateShape => {
}, []);

useEffect(() => {
const subscription = ExpoBattery.addBatteryLevelListener(({ batteryLevel }) => {
const remove = batterLevelSubject.current.addListener(batteryLevel => {
dispatch(Action.batteryLevelUpdated(batteryLevel));
});

Expand All @@ -135,7 +181,7 @@ export const usePowerState = (): PowerStateShape => {

getInitialBatteryLevel();

return () => subscription.remove();
return () => remove();
}, []);

useEffect(() => {
Expand Down

0 comments on commit c3b7e07

Please sign in to comment.