UNPKG

1.84 kBJavaScriptView Raw
1// @flow
2
3import { NativeEventEmitter, Platform } from 'react-native';
4
5type NativeModule = {
6 startObserving: ?() => void,
7 stopObserving: ?() => void,
8};
9
10type Subscription = {
11 remove: () => void,
12};
13
14class EventEmitter {
15 _listenersCount = 0;
16 _nativeModule: NativeModule;
17 _eventEmitter: NativeEventEmitter;
18
19 constructor(nativeModule: NativeModule) {
20 this._nativeModule = nativeModule;
21 this._eventEmitter = new NativeEventEmitter(nativeModule);
22 }
23
24 addListener<T>(eventName: string, listener: T => void): Subscription {
25 this._listenersCount += 1;
26 if (Platform.OS === 'android' && this._nativeModule.startObserving) {
27 if (this._listenersCount === 1) {
28 // We're not awaiting start of updates
29 // they should start shortly.
30 this._nativeModule.startObserving();
31 }
32 }
33 return this._eventEmitter.addListener(eventName, listener);
34 }
35
36 removeAllListeners(eventName: string): void {
37 const listenersToRemoveCount = this._eventEmitter.listeners(eventName).length;
38 const newListenersCount = Math.max(0, this._listenersCount - listenersToRemoveCount);
39
40 if (Platform.OS === 'android' && this._nativeModule.stopObserving && newListenersCount === 0) {
41 this._nativeModule.stopObserving();
42 }
43
44 this._eventEmitter.removeAllListeners(eventName);
45 this._listenersCount = newListenersCount;
46 }
47
48 removeSubscription(subscription: Subscription): void {
49 this._listenersCount -= 1;
50
51 if (Platform.OS === 'android' && this._nativeModule.stopObserving) {
52 if (this._listenersCount === 0) {
53 this._nativeModule.stopObserving();
54 }
55 }
56
57 this._eventEmitter.removeSubscription(subscription);
58 }
59
60 emit(eventType: string, ...params: Array<*>) {
61 this._eventEmitter.emit(eventType, ...params);
62 }
63}
64
65module.exports = EventEmitter;