Event Listeners are getting increased in Event Emitter

126 Views Asked by At

I'm using server sent events and on connection for event or something to change in app, I'm listening to event emitted by nest js event emitter.

I have setup event emitter in few API's interceptor after response.

And on new SSE connections listeners are getting increased and this may create memory leak issue as max limit is 10, but on every SSE API new listeners should not be there as I'm, closing listeners in req.on('close')

When client refreshes page SSE API is called along with that listeners are there. If I again refresh API, it goes to close and do all console, also it close 1 listener, and console in res.on close are getting printed twice. and listeners are increasing the number of times sse api is called.

Thanks in advance for any help!

controller.ts

  fetchDataEVents(
    @Query() query,
    @Res() res,
    @ReqUser() user: UserDto
  ): Observable<Partial<MessageEvent>> {
    console.log(`In stream for data`, query.dataId);
    const subject$ = new Subject();
    this.sseService.commonEventEmitter2(query, subject$, user, res);
    return subject$.pipe(
      map(({ data, type }: MessageEvent) => ({ data, type }))
    );
  }

eventEmitter.ts

 commonEventEmitter2(query, subject$, user, res) {
    const dataHandler= () => {
      console.log(
        `data event listened for event : : : data.updated.${query.dataId} `
      );
      const eventData = this.dataUpdateChanges(query, user);
      from(eventData).subscribe((data) => {
        subject$.next({
          data: {
            fetchData: data[0],
            
          },
          type: serverSentEventType.DATA_UPDATED,
        });
      });
    };
    
    this.eventEmitter.on(`data.updated.${query.dataId}`, dataHandler);

  

      this.eventEmitter.removeListener(
        `data.updated.${query.dataId}`,
        dataHandler
      );
     
      console.log(
        `count after`,
        this.eventEmitter.listenerCount(`data.updated.${query.dataId}`)
      );
    });
  }
0

There are 0 best solutions below