Files
taskbuffer/ts/taskbuffer.classes.taskdebounced.ts

40 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-03-25 12:14:49 +01:00
import * as plugins from './taskbuffer.plugins.js';
2020-07-12 02:40:45 +00:00
2023-08-02 00:07:21 +02:00
import { Task, type ITaskFunction } from './taskbuffer.classes.task.js';
import { logger } from './taskbuffer.logging.js';
2020-07-12 02:40:45 +00:00
export class TaskDebounced<T = unknown> extends Task {
private _debouncedTaskFunction: ITaskFunction;
private _observableIntake = new plugins.smartrx.ObservableIntake<T>();
constructor(optionsArg: {
name: string;
taskFunction: ITaskFunction;
2020-07-12 10:57:15 +00:00
debounceTimeInMillis: number;
2020-07-12 02:40:45 +00:00
}) {
super({
name: optionsArg.name,
taskFunction: async (x: T) => {
this._observableIntake.push(x);
2020-09-02 13:04:52 +00:00
},
2020-07-12 02:40:45 +00:00
});
this.taskFunction = optionsArg.taskFunction;
2020-09-02 13:04:52 +00:00
this._observableIntake.observable
.pipe(
plugins.smartrx.rxjs.ops.debounceTime(optionsArg.debounceTimeInMillis),
)
.subscribe({
next: async (x) => {
try {
await this.taskFunction(x);
} catch (err) {
logger.log('error', `TaskDebounced "${this.name || 'unnamed'}" failed: ${err instanceof Error ? err.message : String(err)}`);
}
},
error: (err) => {
logger.log('error', `TaskDebounced "${this.name || 'unnamed'}" observable error: ${err instanceof Error ? err.message : String(err)}`);
},
2020-09-02 13:04:52 +00:00
});
2020-07-12 02:40:45 +00:00
}
2020-09-02 13:04:52 +00:00
}