Skip to content

Commit

Permalink
refactor(rtc): add readable()
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrious committed Mar 21, 2023
1 parent 589a3a7 commit e74e40e
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions packages/agora-rtc-react/src/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { Disposer } from "./utils";

/** Callback to inform of a value updates. */
export type Subscriber<T> = (value: T) => void;

/** Start and stop notification callbacks. */
export type StartStopNotifier<T> = (set: Subscriber<T>) => Disposer | void;

/** Readable interface for subscribing. */
export interface Readable<T> {
/**
* Subscribe on value changes.
* @param run subscription callback
*/
subscribe(this: void, run: Subscriber<T>): Disposer;
}

export function readable<T>(value: T, start: StartStopNotifier<T>): Readable<T> {
let stop: Disposer | null | undefined;
const subscribers = new Set<Subscriber<T>>();

function set(newValue: T) {
if (!Object.is(value, newValue)) {
value = newValue;
if (stop) {
for (const subscriber of subscribers) {
subscriber(value);
}
}
}
}

function subscribe(run: Subscriber<T>) {
subscribers.add(run);
if (subscribers.size === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
subscribers.delete(run);
if (subscribers.size === 0 && stop) {
stop();
stop = null;
}
};
}

return { subscribe };
}

function noop() {
// noop
}

0 comments on commit e74e40e

Please sign in to comment.