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

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

Parameters

Name

Type

Description

key

string

Identifier to group related callbacks.

callbacks

Record<string, Callback[]>

Object mapping keys to arrays of callback functions.

callback

Callback

The callback function to be subscribed under the given key.

Returns

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


Interaction with Other System Parts


Mermaid Diagram

classDiagram
    class subscribeCallback {
        +Callback[] keyedRevalidators
        +subscribeCallback(key: string, callbacks: Record<string, Callback[]>, callback: Callback): () => void
    }
    subscribeCallback : -index: number
    subscribeCallback : -unsubscribe()

Diagram Explanation:


Summary

This file can be integrated into larger systems requiring flexible subscription management, such as state management libraries, cache invalidation systems, or custom event emitters.