1 | import invariant from 'invariant';
|
2 | import { NativeEventEmitter, Platform } from 'react-native';
|
3 | const nativeEmitterSubscriptionKey = '@@nativeEmitterSubscription@@';
|
4 | export class EventEmitter {
|
5 | constructor(nativeModule) {
|
6 | this._listenerCount = 0;
|
7 | this._nativeModule = nativeModule;
|
8 | this._eventEmitter = new NativeEventEmitter(nativeModule);
|
9 | }
|
10 | addListener(eventName, listener) {
|
11 | if (!this._listenerCount && Platform.OS !== 'ios' && this._nativeModule.startObserving) {
|
12 | this._nativeModule.startObserving();
|
13 | }
|
14 | this._listenerCount++;
|
15 | const nativeEmitterSubscription = this._eventEmitter.addListener(eventName, listener);
|
16 | const subscription = {
|
17 | [nativeEmitterSubscriptionKey]: nativeEmitterSubscription,
|
18 | remove: () => {
|
19 | this.removeSubscription(subscription);
|
20 | },
|
21 | };
|
22 | return subscription;
|
23 | }
|
24 | removeAllListeners(eventName) {
|
25 | const removedListenerCount = this._eventEmitter.listeners(eventName).length;
|
26 | this._eventEmitter.removeAllListeners(eventName);
|
27 | this._listenerCount -= removedListenerCount;
|
28 | invariant(this._listenerCount >= 0, `EventEmitter must have a non-negative number of listeners`);
|
29 | if (!this._listenerCount && Platform.OS !== 'ios' && this._nativeModule.stopObserving) {
|
30 | this._nativeModule.stopObserving();
|
31 | }
|
32 | }
|
33 | removeSubscription(subscription) {
|
34 | const nativeEmitterSubscription = subscription[nativeEmitterSubscriptionKey];
|
35 | if (!nativeEmitterSubscription) {
|
36 | return;
|
37 | }
|
38 | this._eventEmitter.removeSubscription(nativeEmitterSubscription);
|
39 | this._listenerCount--;
|
40 |
|
41 |
|
42 | delete subscription[nativeEmitterSubscriptionKey];
|
43 |
|
44 | subscription.remove = () => { };
|
45 | if (!this._listenerCount && Platform.OS !== 'ios' && this._nativeModule.stopObserving) {
|
46 | this._nativeModule.stopObserving();
|
47 | }
|
48 | }
|
49 | emit(eventName, ...params) {
|
50 | this._eventEmitter.emit(eventName, ...params);
|
51 | }
|
52 | }
|
53 |
|
\ | No newline at end of file |