Skip to content

Commit

Permalink
Merge pull request #683 from JoL0712/master
Browse files Browse the repository at this point in the history
Multiple event listener support
  • Loading branch information
manuquentin authored Jun 9, 2023
2 parents 70059bd + 0eb8f36 commit aa681cb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
6 changes: 5 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ declare module 'react-native-callkeep' {
}
};

export class EventListener {
remove(): void
}

export default class RNCallKeep {
static getInitialEvents(): Promise<InitialEvents>

Expand All @@ -110,7 +114,7 @@ declare module 'react-native-callkeep' {
static addEventListener<Event extends Events>(
type: Event,
handler: (args: EventsPayload[Event]) => void,
): void
): EventListener

static removeEventListener(type: Events): void

Expand Down
39 changes: 33 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ const CONSTANTS = {

export { emit, CONSTANTS };

class EventListener {
constructor(type, listener, callkeep) {
this._type = type;
this._listener = listener;
this._callkeep = callkeep;
}

remove = () => {
this._callkeep.removeEventListener(this._type, this._listener);
};
}

class RNCallKeep {
constructor() {
this._callkeepEventHandlers = new Map();
Expand All @@ -27,17 +39,32 @@ class RNCallKeep {
addEventListener = (type, handler) => {
const listener = listeners[type](handler);

this._callkeepEventHandlers.set(type, listener);
const listenerSet = this._callkeepEventHandlers.get(type) ?? new Set();
listenerSet.add(listener);

this._callkeepEventHandlers.set(type, listenerSet);

return new EventListener(type, listener, this);
};

removeEventListener = (type) => {
const listener = this._callkeepEventHandlers.get(type);
if (!listener) {
removeEventListener = (type, listener = undefined) => {
const listenerSet = this._callkeepEventHandlers.get(type);
if (!listenerSet) {
return;
}

listener.remove();
this._callkeepEventHandlers.delete(type);
if (listener) {
listenerSet.delete(listener);
listener.remove();
if (listenerSet.size <= 0) {
this._callkeepEventHandlers.delete(type);
}
} else {
listenerSet.forEach((listener) => {
listener.remove();
});
this._callkeepEventHandlers.delete(type);
}
};

setup = async (options) => {
Expand Down

0 comments on commit aa681cb

Please sign in to comment.