Error when interconnecting ipcRenderer and ipcMain in electron

I have configured cli angular in electron, and I have a link where it execute a function that intercomunicate ipcRenderer and ipcMain:

html:

<a (click)="check()"> click </a>

component:

constructor(private _e: ElectronService) { }

check () {
   this._e.ipcRenderer.send ('conn', 'round');
   this._e.ipcRenderer.on ('conn-st', (event, args) => {
      console.log (args);
   });
}

main.js (electron):

ipcMain.on ('conn', function (event, args) {
  event.sender.send ('conn-st', 'trip');
});

The problem is that when you click once, you do it once, but when you click again it does 3, then 4, 5 and so on continuously.

And throws this error upon reaching 11:

(node:23006) Error: Possible EventEmitter memory leak detected. 11 conn-st listeners added. Use emitter.setMaxListeners() to increase limit

How do I end the connection between ipcRenderer and ipcMain?

Upvotes: 0

Views: 3313

Answers (2)

Alexander Leithner
Alexander Leithner

Reputation: 3432

That error message only says, that 11 listeners to a "socket" (like the ones in UNIX) were created. Every listener creates a unique ID which is returned when creating the listener. Based on that, removing one particular listener could be done like this:

// Create a listener.
var myListener = function (event, args) {} 
ipcRenderer.on("channel", myListener);

// Delete only this one by its ID:
ipcRenderer.removeListener("channel", myListener);

But you can also delete all of the listeners that were created for a socket, like this:

// Create a few listeners.
var myListener0 = function (event, args) {};
var myListener1 = function (event, args) {};
var myListener2 = function (event, args) {};
var myListener3 = function (event, args) {};

//
ipcRenderer.on("channel", myListener0);
ipcRenderer.on("channel", myListener1);
ipcRenderer.on("channel", myListener2);
ipcRenderer.on("channel", myListener3);

// Delete all listeners for socket "channel".
ipcRenderer.removeAllListeners("channel");

This is also covered in the Electron documentation, particularly here.

Upvotes: 6

The accepted answer is nolonger correct as per the electron documentation documentation. The listener is a function and should be removed as shown below.

// Create a listener
let listener = (event, args) => {}
ipcRenderer.on("channel", listener );

//Delete the listener
ipcRenderer.removeListener("parse-cm-request", listener);

Upvotes: 1

Related Questions