Files
ThreadNet-Web/src/utils/Whenable.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

80 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-07-29 16:53:26 -06:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
2020-07-29 16:53:26 -06:00
Copyright 2020 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
2020-07-29 16:53:26 -06:00
*/
2021-10-22 17:23:32 -05:00
import { logger } from "matrix-js-sdk/src/logger";
2020-07-29 16:53:26 -06:00
import { IDestroyable } from "./IDestroyable";
import { arrayFastClone } from "./arrays";
export type WhenFn<T extends string | number> = (w: Whenable<T>) => void;
2020-07-29 16:53:26 -06:00
/**
* Whenables are a cheap way to have Observable patterns mixed with typical
* usage of Promises, without having to tear down listeners or calls. Whenables
* are intended to be used when a condition will be met multiple times and
* the consumer needs to know *when* that happens.
*/
export abstract class Whenable<T extends string | number> implements IDestroyable {
2020-07-29 16:53:26 -06:00
private listeners: { condition: T | null; fn: WhenFn<T> }[] = [];
/**
* Sets up a call to `fn` *when* the `condition` is met.
* @param condition The condition to match.
* @param fn The function to call.
* @returns This.
*/
public when(condition: T, fn: WhenFn<T>): Whenable<T> {
2021-06-29 13:11:58 +01:00
this.listeners.push({ condition, fn });
2020-07-29 16:53:26 -06:00
return this;
}
/**
2020-07-31 09:41:19 -06:00
* Sets up a call to `fn` *when* any of the `conditions` are met.
2020-07-29 16:53:26 -06:00
* @param conditions The conditions to match.
* @param fn The function to call.
* @returns This.
*/
public whenAnyOf(conditions: T[], fn: WhenFn<T>): Whenable<T> {
for (const condition of conditions) {
this.when(condition, fn);
}
return this;
}
/**
* Sets up a call to `fn` *when* any condition is met.
* @param fn The function to call.
* @returns This.
*/
public whenAnything(fn: WhenFn<T>): Whenable<T> {
2021-06-29 13:11:58 +01:00
this.listeners.push({ condition: null, fn });
2020-07-29 16:53:26 -06:00
return this;
}
/**
2020-07-31 09:41:19 -06:00
* Notifies all the listeners of a given condition.
2020-07-29 16:53:26 -06:00
* @param condition The new condition that has been met.
*/
protected notifyCondition(condition: T): void {
2020-07-29 16:53:26 -06:00
const listeners = arrayFastClone(this.listeners); // clone just in case the handler modifies us
for (const listener of listeners) {
if (listener.condition === null || listener.condition === condition) {
try {
listener.fn(this);
} catch (e) {
2021-10-15 16:30:53 +02:00
logger.error(`Error calling whenable listener for ${condition}:`, e);
2020-07-29 16:53:26 -06:00
}
}
}
}
public destroy(): void {
2020-07-29 16:53:26 -06:00
this.listeners = [];
}
}