From 2e994de0eb62bf9616c39003d06eae93beb28357 Mon Sep 17 00:00:00 2001 From: Vitaly Tomilov Date: Mon, 30 Sep 2024 00:43:47 +0100 Subject: [PATCH] fixing #33 --- src/event.ts | 14 ++++++++++---- test/event.spec.ts | 5 ++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/event.ts b/src/event.ts index 55d8366..871892d 100644 --- a/src/event.ts +++ b/src/event.ts @@ -361,6 +361,12 @@ export class SubEvent { const onError = typeof options?.onError === 'function' && options.onError; const start = schedule === EmitSchedule.sync ? Stat.callNow : Stat.callNext; const middle = schedule === EmitSchedule.async ? Stat.callNext : Stat.callNow; + const onLast = (count: number) => { + this._lastEvent = data; // save the last event + if (onFinished) { + onFinished(count); // notify + } + }; start(() => { const r = this._getRecipients(); r.forEach((sub, index) => middle(() => { @@ -378,12 +384,12 @@ export class SubEvent { } if (index === r.length - 1) { // the end of emission reached; - this._lastEvent = data; // save the last event - if (onFinished) { - onFinished(r.length); // notify - } + onLast(r.length); } })); + if (!r.length) { + onLast(0); + } }); return this; } diff --git a/test/event.spec.ts b/test/event.spec.ts index 3c27029..b2338cf 100644 --- a/test/event.spec.ts +++ b/test/event.spec.ts @@ -461,9 +461,8 @@ describe('toConsumer', () => { describe('lastEvent', () => { it('must be set once emission finished', done => { const e = new SubEvent(); - e.subscribe(dummy); // TODO: Should not be needed with #33 is resolved? - const onFinished = (count: number) => { + const onFinished = () => { expect(e.lastEvent).to.eq(123); }; @@ -472,7 +471,7 @@ describe('lastEvent', () => { expect(e.lastEvent).to.be.undefined; setTimeout(() => { - expect(handler).to.have.been.called.with(1); + expect(handler).to.have.been.called.with(0); done(); }); });