Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: lifecycle hook should trigger only one time #168

Merged
merged 2 commits into from
Aug 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/lifecycle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ export class LifecycleManager {
if (!Array.isArray(fnList)) {
return;
}
// lifecycle hook should only trigger one time
this.hookFnMap.delete(hookName);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不是所有的 hook 都只执行一次吧?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

有需要执行多次的 hook 吗?好像也没有把?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

设计上确实应该执行一次,如果有多次触发的类似事件分发机制的场景,就不该通过 Lifecycle 做,应该考虑 Trigger 或者 EventEmitter

for (const hookFn of fnList) {
await hookFn({
app: this.app,
Expand Down
38 changes: 38 additions & 0 deletions test/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,42 @@ describe('test/lifecycle.test.ts', () => {
'app_beforeClose',
]);
});

it('should not trigger lifecyle multi times', async () => {
const appWithLifeCyclePath = path.resolve(__dirname, './fixtures/app_with_lifecycle');
const app = await createApp(appWithLifeCyclePath);
const lifecycleList = app.container.get(LifecycleList).lifecycleList;
await Promise.all([
app.run(),
app.run(),
app.run(),
]);

await Promise.all([
app.close(),
app.close(),
app.close(),
]);

assert.deepStrictEqual(lifecycleList, [
'pluginA_configWillLoad',
'pluginB_configWillLoad',
'app_configWillLoad',
'pluginA_configDidLoad',
'pluginB_configDidLoad',
'app_configDidLoad',
'pluginA_didLoad',
'pluginB_didLoad',
'app_didLoad',
'pluginA_willReady',
'pluginB_willReady',
'app_willReady',
'pluginA_didReady',
'pluginB_didReady',
'app_didReady',
'pluginA_beforeClose',
'pluginB_beforeClose',
'app_beforeClose',
]);
});
});