Skip to content

Commit

Permalink
Added waitFor method in PubSub
Browse files Browse the repository at this point in the history
  • Loading branch information
dPaskhin committed May 3, 2024
1 parent 0c32715 commit 5935fa3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/main/PubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,23 @@ export class PubSub<T = void> {
}
}

/**
* Waits for a message that satisfies the given predicate to be published and resolves with that message.
*
* @param predicate A function that takes the message as a parameter and returns true if the message satisfies the condition, otherwise false.
* @returns A promise that resolves with the published message that satisfies the predicate.
*/
waitFor(predicate: (message: T) => boolean): Promise<T> {
return new Promise(resolve => {
const unsubscribe = this.subscribe(message => {
if (predicate(message)) {
resolve(message);
unsubscribe();
}
});
});
}

/**
* Adds a listener that would receive all messages published via {@link publish}.
*
Expand Down
40 changes: 39 additions & 1 deletion src/test/PubSub.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PubSub } from '../main';
import { PubSub, delay } from '../main';

describe('PubSub', () => {
test('publishes a message', () => {
Expand Down Expand Up @@ -54,4 +54,42 @@ describe('PubSub', () => {
expect(listenerMock1).toHaveBeenCalledTimes(0);
expect(listenerMock2).toHaveBeenCalledTimes(1);
});

test('waits for a specific message and resolves with that message', () => {
const pubSub = new PubSub<number>();

pubSub
.waitFor(message => message === 42)
.then(message => {
expect(message).toBe(42);
});

pubSub.publish(10);
pubSub.publish(20);
pubSub.publish(42);
pubSub.publish(30);
});

test('does not resolve if no message matches the predicate', () => {
const listenerMock = jest.fn();
const pubSub = new PubSub<number>();

let result: number;

pubSub
.waitFor(message => message === 42)
.then(message => {
result = message;
listenerMock();
});

pubSub.publish(10);
pubSub.publish(20);
pubSub.publish(30);

delay(100).then(() => {
expect(result).toBeUndefined();
expect(listenerMock).toHaveBeenCalledTimes(0);
});
});
});

0 comments on commit 5935fa3

Please sign in to comment.