1 | import { EventEmitter, Subscription, Platform } from '@unimodules/core';
|
2 |
|
3 | type Listener<E> = (event: E) => void;
|
4 |
|
5 | type NativeSensorModule = any;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | export default class DeviceSensor<M> {
|
12 | _nativeModule: NativeSensorModule;
|
13 | _nativeEmitter: EventEmitter;
|
14 | _nativeEventName: string;
|
15 | _listenerCount: number;
|
16 |
|
17 | constructor(nativeSensorModule: NativeSensorModule, nativeEventName: string) {
|
18 | this._nativeModule = nativeSensorModule;
|
19 | this._nativeEmitter = new EventEmitter(nativeSensorModule);
|
20 | this._nativeEventName = nativeEventName;
|
21 | this._listenerCount = 0;
|
22 | }
|
23 |
|
24 | addListener(listener: Listener<M>): Subscription {
|
25 | let subscription = this._nativeEmitter.addListener(this._nativeEventName, listener);
|
26 | subscription.remove = () => this.removeSubscription(subscription);
|
27 | this._listenerCount++;
|
28 | return subscription;
|
29 | }
|
30 |
|
31 | hasListeners(): boolean {
|
32 | return this._listenerCount > 0;
|
33 | }
|
34 |
|
35 | getListenerCount(): number {
|
36 | return this._listenerCount;
|
37 | }
|
38 |
|
39 | removeAllListeners(): void {
|
40 | this._listenerCount = 0;
|
41 | this._nativeEmitter.removeAllListeners(this._nativeEventName);
|
42 | }
|
43 |
|
44 | removeSubscription(subscription: Subscription): void {
|
45 | this._listenerCount--;
|
46 | this._nativeEmitter.removeSubscription(subscription);
|
47 | }
|
48 |
|
49 | setUpdateInterval(intervalMs: number): void {
|
50 | if (!this._nativeModule.setUpdateInterval) {
|
51 | console.warn(`expo-sensors: setUpdateInterval() is not supported on ${Platform.OS}`);
|
52 | } else {
|
53 | this._nativeModule.setUpdateInterval(intervalMs);
|
54 | }
|
55 | }
|
56 | async isAvailableAsync(): Promise<boolean> {
|
57 | if (!this._nativeModule.isAvailableAsync) {
|
58 | return false;
|
59 | } else {
|
60 | return await this._nativeModule.isAvailableAsync();
|
61 | }
|
62 | }
|
63 | }
|