简体   繁体   中英

NestJS SSE memory leak

I want to use "Server Side Events" to notify all clients. I didn't find a way to do a broadcast, so I decided to use the Eventemitter internally. This causes a memory leak. How can I broadcast or unsubscribe from the Eventemitter when the sse is broken (I think this is a bad solution)

My bad problem solution

thanks for asking a question on StackOverFlow!

NOTE: It would be better for the next time if you submit your code in text format instead of screenshot:)

Judging by the code you've provided, you are registering a new listener every time the Event is triggered by the server, which will trigger the event n^2 times of the events emitted.

You have 2 solutions which you can implement:

  1. Check if 'channel.bindAccount' event is already registered and do not register again. I wouldn't recommend this solution but it can be done.
  2. Register the event on your constructor and emit that in the sse. Example code:
constructor() {
  const event = new Subject<MessageEvent>();
  this.eventEmitter.on('channel.bindAccount', (payload) => {
    console.log(payload);
    event.next({data: payload} as MessageEvent);
  });
}
@Public()
@Sse('event')
event(): Observable<MessageEvent> {
  this.eventEmitter.emit('channel.bindAccount', (payload));
}

Registering the event in the constructor and emitting it on the sse is the idea, however I am not entirely sure where exactly payload comes from and I didn't test the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM