Skip to content

Commit

Permalink
fix(core): reducing service listener count
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 21, 2022
1 parent 3a63ca0 commit ee29094
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 19 deletions.
27 changes: 8 additions & 19 deletions packages/core/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,15 +276,16 @@ export class Context {
disposables: [],
})

const dispose = this.on('service', async (name) => {
if (!using.includes(name)) return
await Promise.allSettled(ctx.state.disposables.slice(1).map(dispose => dispose()))
callback()
})

this.state.children.push(plugin)
this.emit('plugin-added', plugin)
ctx.state.disposables.push(dispose)

if (using.length) {
ctx.on('service', async (name) => {
if (!using.includes(name)) return
await Promise.allSettled(ctx.state.disposables.slice(1).map(dispose => dispose()))
callback()
})
}

const callback = () => {
if (using.some(name => !this[name])) return
Expand Down Expand Up @@ -606,23 +607,11 @@ export namespace Context {
this.emit('service', key)
const action = value ? oldValue ? 'changed' : 'enabled' : 'disabled'
this.logger('service').debug(key, action)
if (value) {
const dispose = () => {
if (this.app[privateKey] !== value) return
this[key] = null
}
this.state.disposables.push(dispose)
this.on('service', (name) => {
if (name !== key) return
remove(this.state.disposables, dispose)
})
}
},
})
}

service('bots')
service('database')
service('model')

export const deprecatedEvents: Dict<EventName & string> = {
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export abstract class Service {
protected stop(): Awaitable<void> {}

constructor(protected ctx: Context, key: keyof Context.Services, immediate?: boolean) {
Context.service(key)
if (immediate) ctx[key] = this as never

ctx.on('ready', async () => {
Expand All @@ -55,6 +56,7 @@ export abstract class Service {
})

ctx.on('dispose', async () => {
if (ctx[key] === this as never) ctx[key] = null
await this.stop()
})
}
Expand Down

0 comments on commit ee29094

Please sign in to comment.