Skip to content

Commit

Permalink
feat: sync callback for store.onInitialized
Browse files Browse the repository at this point in the history
  • Loading branch information
geekact committed Dec 18, 2022
1 parent cd4155d commit 091da46
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/store/modelStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,16 @@ export class ModelStore extends StoreBasic<Record<string, any>> {
this.topic.publish('unmount');
}

onInitialized(): Promise<void> {
onInitialized(maybeSync?: () => void): Promise<void> {
return new Promise((resolve) => {
if (this._isReady) {
maybeSync?.();
resolve();
} else {
this.topic.subscribeOnce('ready', resolve);
this.topic.subscribeOnce('ready', () => {
maybeSync?.();
resolve();
});
}
});
}
Expand Down
23 changes: 22 additions & 1 deletion test/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ test('Get custom compose', () => {
process.env.NODE_ENV = prevEnv;
});

it('rxjs can observe store', () => {
test('rxjs can observe store', () => {
store.init();

const observable = from(store);
Expand Down Expand Up @@ -315,3 +315,24 @@ it('rxjs can observe store', () => {
]),
);
});

test('async callback for onInitialized', () => {
let msg = 'a';
store.onInitialized(() => {
msg += 'b';
});
msg += 'c';
store.init();
expect(msg).toBe('acb');
});

test('sync callback for onInitialized', () => {
store.init();

let msg = 'a';
store.onInitialized(() => {
msg += 'b';
});
msg += 'c';
expect(msg).toBe('abc');
});

0 comments on commit 091da46

Please sign in to comment.