Skip to content

Commit

Permalink
RN: Rewrite NativeEventEmitter
Browse files Browse the repository at this point in the history
Summary:
Rewrites `NativeEventEmitter` to not extend `EventEmitter` and to compose `RCTDeviceEventEmitter` instead of (mis)using its exported `sharedSubscriber` property.

This makes it easier to reason about `NativeEventEmitter`. Also, the extraneous methods on `EventEmitter` are no longer inherited.

Changelog:
[General][Removed] - `NativeEventEmitter` no longer inherits from `EventEmitter`, so it no longer implements `removeListener` and `removeSubscription`. Instead, use the `remove()` method on the subscription object returned by `addListener`.

Reviewed By: rubennorte

Differential Revision: D26163562

fbshipit-source-id: c1aadb99bdefbaa36fece57ce74604e414f94d4d
  • Loading branch information
yungsters authored and facebook-github-bot committed Feb 10, 2021
1 parent 7d4612b commit d39643b
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 42 deletions.
101 changes: 65 additions & 36 deletions Libraries/EventEmitter/NativeEventEmitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,67 +4,96 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @flow
*/

'use strict';

import {
type EventSubscription,
type IEventEmitter,
} from '../vendor/emitter/EventEmitter';
import Platform from '../Utilities/Platform';
import EventEmitter from '../vendor/emitter/EventEmitter';
import type EmitterSubscription from '../vendor/emitter/_EmitterSubscription';
import RCTDeviceEventEmitter from './RCTDeviceEventEmitter';
import invariant from 'invariant';

type NativeModule = {
+addListener: (eventType: string) => void,
+removeListeners: (count: number) => void,
type NativeModule = $ReadOnly<{
addListener: (eventType: string) => void,
removeListeners: (count: number) => void,
...
};
}>;

export type {EventSubscription};

/**
* Abstract base class for implementing event-emitting modules. This implements
* a subset of the standard EventEmitter node module API.
* `NativeEventEmitter` is intended for use by Native Modules to emit events to
* JavaScript listeners. If a `NativeModule` is supplied to the constructor, it
* will be notified (via `addListener` and `removeListeners`) when the listener
* count changes to manage "native memory".
*
* Currently, all native events are fired via a global `RCTDeviceEventEmitter`.
* This means event names must be globally unique, and it means that call sites
* can theoretically listen to `RCTDeviceEventEmitter` (although discouraged).
*/
export default class NativeEventEmitter<
EventDefinitions: {...},
> extends EventEmitter<EventDefinitions> {
export default class NativeEventEmitter<TEventToArgsMap: {...}>
implements IEventEmitter<TEventToArgsMap> {
_nativeModule: ?NativeModule;

constructor(nativeModule: ?NativeModule) {
super(RCTDeviceEventEmitter.sharedSubscriber);
if (Platform.OS === 'ios') {
invariant(nativeModule, 'Native module cannot be null.');
invariant(
nativeModule != null,
'`new NativeEventEmitter()` requires a non-null argument.',
);
this._nativeModule = nativeModule;
}
}

addListener<K: $Keys<EventDefinitions>>(
eventType: K,
listener: (...$ElementType<EventDefinitions, K>) => mixed,
context: $FlowFixMe,
): EmitterSubscription<EventDefinitions, K> {
if (this._nativeModule != null) {
this._nativeModule.addListener(eventType);
}
return super.addListener(eventType, listener, context);
addListener<TEvent: $Keys<TEventToArgsMap>>(
eventType: TEvent,
listener: (...args: $ElementType<TEventToArgsMap, TEvent>) => mixed,
context?: mixed,
): EventSubscription {
this._nativeModule?.addListener(eventType);
let subscription: ?EventSubscription = RCTDeviceEventEmitter.addListener(
eventType,
listener,
context,
);

return {
remove: () => {
if (subscription != null) {
this._nativeModule?.removeListeners(1);
subscription.remove();
subscription = null;
}
},
};
}

removeAllListeners<K: $Keys<EventDefinitions>>(eventType: ?K): void {
invariant(eventType, 'eventType argument is required.');
const count = this.listenerCount(eventType);
if (this._nativeModule != null) {
this._nativeModule.removeListeners(count);
}
super.removeAllListeners(eventType);
emit<TEvent: $Keys<TEventToArgsMap>>(
eventType: TEvent,
...args: $ElementType<TEventToArgsMap, TEvent>
): void {
// Generally, `RCTDeviceEventEmitter` is directly invoked. But this is
// included for completeness.
RCTDeviceEventEmitter.emit(eventType, ...args);
}

removeSubscription<K: $Keys<EventDefinitions>>(
subscription: EmitterSubscription<EventDefinitions, K>,
removeAllListeners<TEvent: $Keys<TEventToArgsMap>>(
eventType?: ?TEvent,
): void {
if (this._nativeModule != null) {
this._nativeModule.removeListeners(1);
}
super.removeSubscription(subscription);
invariant(
eventType != null,
'`NativeEventEmitter.removeAllListener()` requires a non-null argument.',
);
this._nativeModule?.removeListeners(this.listenerCount(eventType));
RCTDeviceEventEmitter.removeAllListeners(eventType);
}

listenerCount<TEvent: $Keys<TEventToArgsMap>>(eventType: TEvent): number {
return RCTDeviceEventEmitter.listenerCount(eventType);
}
}
12 changes: 6 additions & 6 deletions Libraries/Utilities/DevSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,27 @@ if (__DEV__) {
const emitter = new NativeEventEmitter<DevSettingsEventDefinitions>(
NativeDevSettings,
);
const menuItems = new Map();
const subscriptions = new Map();

DevSettings = {
addMenuItem(title: string, handler: () => mixed): void {
// Make sure items are not added multiple times. This can
// happen when hot reloading the module that registers the
// menu items. The title is used as the id which means we
// don't support multiple items with the same name.
const oldHandler = menuItems.get(title);
if (oldHandler != null) {
emitter.removeListener('didPressMenuItem', oldHandler);
let subscription = subscriptions.get(title);
if (subscription != null) {
subscription.remove();
} else {
NativeDevSettings.addMenuItem(title);
}

menuItems.set(title, handler);
emitter.addListener('didPressMenuItem', event => {
subscription = emitter.addListener('didPressMenuItem', event => {
if (event.title === title) {
handler();
}
});
subscriptions.set(title, subscription);
},
reload(reason?: string): void {
if (NativeDevSettings.reloadWithReason != null) {
Expand Down
34 changes: 34 additions & 0 deletions Libraries/vendor/emitter/EventEmitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,37 @@ import type {EventSubscription} from './EventSubscription';
export default EventEmitter;

export type {EventSubscription};

/**
* Essential interface for an EventEmitter.
*/
export interface IEventEmitter<TEventToArgsMap: {...}> {
/**
* Registers a listener that is called when the supplied event is emitted.
* Returns a subscription that has a `remove` method to undo registration.
*/
addListener<TEvent: $Keys<TEventToArgsMap>>(
eventType: TEvent,
listener: (...args: $ElementType<TEventToArgsMap, TEvent>) => void,
context?: mixed,
): EventSubscription;

/**
* Emits the supplied event. Additional arguments supplied to `emit` will be
* passed through to each of the registered listeners.
*/
emit<TEvent: $Keys<TEventToArgsMap>>(
eventType: TEvent,
...args: $ElementType<TEventToArgsMap, TEvent>
): void;

/**
* Removes all registered listeners.
*/
removeAllListeners<TEvent: $Keys<TEventToArgsMap>>(eventType?: ?TEvent): void;

/**
* Returns the number of registered listeners for the supplied event.
*/
listenerCount<TEvent: $Keys<TEventToArgsMap>>(eventType: TEvent): number;
}

0 comments on commit d39643b

Please sign in to comment.