subscribe-key.ts
Overview
The subscribe-key.ts file provides a utility function to manage subscription callbacks that are grouped by unique keys. Its primary purpose is to allow clients to register callback functions under specific keys and to obtain an unsubscribe function that can later remove the registered callback efficiently. This pattern is useful in event-driven architectures or reactive programming scenarios where multiple listeners need to respond to changes or events identified by keys.
Detailed Explanation
Type Aliases
type Callback = (...args: any[]) => any
Description:
Defines a generic callback type that accepts any number of arguments of any type and can return any value.Use Case:
Represents subscriber callback functions in a flexible manner, allowing for various signatures.
Function: subscribeCallback
export const subscribeCallback = (
key: string,
callbacks: Record<string, Callback[]>,
callback: Callback
) => {
const keyedRevalidators = callbacks[key] || (callbacks[key] = [])
keyedRevalidators.push(callback)
return () => {
const index = keyedRevalidators.indexOf(callback)
if (index >= 0) {
// O(1): faster than splice
keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1]
keyedRevalidators.pop()
}
}
}
Purpose
Adds a callback function to a collection of callbacks associated with a specific key.
Returns an unsubscribe function that, when invoked, removes the callback from the collection efficiently.
Parameters
Name | Type | Description |
|---|---|---|
|
| Identifier to group related callbacks. |
|
| Object mapping keys to arrays of callback functions. |
|
| The callback function to be subscribed under the given key. |
Returns
() => void— An unsubscribe function that removes the previously subscribed callback from the callbacks collection.
Usage Example
const callbacks: Record<string, Callback[]> = {};
// Subscribe a callback under the key 'user-update'
const unsubscribe = subscribeCallback('user-update', callbacks, (data) => {
console.log('User updated:', data);
});
// Later, to unsubscribe the callback:
unsubscribe();
Implementation Details
Keyed Callback Storage:
The function checks if thecallbacksobject has an array assigned for the givenkey. If not, it initializes an empty array.Adding the Callback:
The callback is appended to the array corresponding to the key.Unsubscribe Mechanism:
The returned function locates the callback's index in the array. To remove the callback in O(1) time (avoiding the overhead ofArray.prototype.splice), it replaces the callback to be removed with the last element in the array and then removes the last element.Performance:
This "swap and pop" approach avoids shifting elements and provides efficient removal when the order of callbacks is not important.
Interaction with Other System Parts
Callback Registry:
This file is intended to be used as a utility for managing sets of keyed callbacks. It assumes that the caller maintains acallbacksobject (a dictionary mapping keys to callback arrays), which may be shared or managed at a higher level in the application.Event or State Management Systems:
ThesubscribeCallbackfunction is likely part of a broader subscription or event notification system, where components or services subscribe to updates keyed by identifiers (e.g., cache keys, event names).Unsubscribe Functionality:
By returning an unsubscribe function, this utility promotes clean resource management and prevents memory leaks by enabling subscribers to deregister their callbacks when no longer needed.
Mermaid Diagram
classDiagram
class subscribeCallback {
+Callback[] keyedRevalidators
+subscribeCallback(key: string, callbacks: Record<string, Callback[]>, callback: Callback): () => void
}
subscribeCallback : -index: number
subscribeCallback : -unsubscribe()
Diagram Explanation:
The
subscribeCallbackfunction manages an internal arraykeyedRevalidatorsof callbacks for a givenkey.It exposes the main method
subscribeCallbackwhich returns anunsubscribefunction that removes the callback from the array.
Summary
The subscribe-key.ts file provides a simple yet efficient mechanism to add and remove callback functions grouped by keys.
It uses an O(1) removal technique to optimize unsubscribe operations.
The file is designed as a utility function and expects the caller to manage the storage object for callbacks.
This utility supports event-driven programming patterns by simplifying management of multiple keyed listeners.
This file can be integrated into larger systems requiring flexible subscription management, such as state management libraries, cache invalidation systems, or custom event emitters.