Adding onClose callback to AsyncIter
This commit is contained in:
@ -7,17 +7,22 @@ interface IAsyncIteratorMessage<T> {
|
||||
close: true | undefined;
|
||||
}
|
||||
export default class AsyncIteratorFromCB<T> implements AsyncIterable<T> {
|
||||
private onData = new Observable<IAsyncIteratorMessage<T>>();
|
||||
#onClose: (() => void)[] = [];
|
||||
#onData = new Observable<IAsyncIteratorMessage<T>>();
|
||||
constructor() {}
|
||||
|
||||
public onClose(callback: () => void) {
|
||||
this.#onClose.push(callback);
|
||||
}
|
||||
|
||||
public getCallback() {
|
||||
return (error: Error | undefined, data: T | undefined) => {
|
||||
this.onData.send({ error, data, close: undefined });
|
||||
this.#onData.send({ error, data, close: undefined });
|
||||
};
|
||||
}
|
||||
|
||||
public send(data: T) {
|
||||
this.onData.send({
|
||||
this.#onData.send({
|
||||
error: undefined,
|
||||
data,
|
||||
close: undefined,
|
||||
@ -25,18 +30,19 @@ export default class AsyncIteratorFromCB<T> implements AsyncIterable<T> {
|
||||
}
|
||||
|
||||
public close() {
|
||||
this.onData.send({
|
||||
this.#onData.send({
|
||||
close: true,
|
||||
data: undefined,
|
||||
error: undefined,
|
||||
});
|
||||
this.onData.close();
|
||||
this.#onData.close();
|
||||
this.#onClose.forEach((cb) => cb());
|
||||
}
|
||||
|
||||
[Symbol.asyncIterator]() {
|
||||
const queue: IAsyncIteratorMessage<T>[] = [];
|
||||
const signal = new Signal();
|
||||
this.onData.subscribe((data) => {
|
||||
this.#onData.subscribe((data) => {
|
||||
queue.push(data);
|
||||
signal.sendSignal();
|
||||
});
|
||||
|
Reference in New Issue
Block a user