Middle+
If you need to support duplicate handlers, how would you implement unsubscription? What are the disadvantages of implementing it through an array with filtering?
sobes.tech AI
Answer from AI
If you need to support duplicate handlers and implement unsubscription, you can store handlers in an array (list) and remove the desired handler during unsubscription.
Disadvantages of implementing with an array and filtering:
- Performance: When removing a handler, a new array without this handler must be created (filtering), which can be costly with a large number of handlers.
- Issues with duplicates: If handlers are duplicated, removing by value can delete all matches, not just a specific instance.
- Identification complexity: Without unique identifiers, it is difficult to precisely remove the needed handler.
How to improve:
- Use a data structure that stores handlers with unique IDs (e.g., Map or an object with keys).
- When adding, return a token or an unsubscribe function that will remove exactly this handler.
Example in JavaScript:
class EventEmitter {
constructor() {
this.handlers = new Map();
this.nextId = 0;
}
on(handler) {
const id = this.nextId++;
this.handlers.set(id, handler);
return () => this.handlers.delete(id); // unsubscribe function
}
emit(event) {
for (const handler of this.handlers.values()) {
handler(event);
}
}
}
This approach allows precise and efficient unsubscription from specific handlers, even if they are duplicated.