Remove all the listeners specific to the user when that user exits the socket

15 Views Asked by At

I am building an app where I can provide the users a feature to bid on their favorite players in real time through a live auction backed up Socket IO. I am using NextJS and Socket IO.

So the problem I am facing right now, is that I need to remove the listeners from the memory that were created when that user joined the auction, now when the user leaves the auction, the listeners that were created should be removed, so that my memory is free.

Right now I am doing this:


io.on("connection", (socket) => {

 const joinListener = async (payload) => {
      // console.log(payload);
      // all of the join auction logic, that involves DB call as well.
    };

 const bidListener = (payload) => {
      const { auctionId, bidderIndex, bidAmount } = payload;
      // Code related to bidding in real time and emitting events to connected members
    };

const exitListener = (payload) => {
      const { auctionId, userId } = payload;

      
        // Logic for exiting the auction

        // here's how I am removing the listeners

        socket.off("join", joinListener);
        socket.off("bid", bidListener);
        socket.off("exit", exitListener);
    
    };

    socket.on("join", joinListener);

    socket.on("bid", bidListener);

    socket.on("exit", exitListener);

}

How should I remove the listeners for the user who is leaving the auction.

Other questions: How can I increase the limit of the listeners from default 10 to some big number, so that I can have multiple auctions running simultaneously without possible memory leaks.

How can I see the list of currently active listeners?

0

There are 0 best solutions below