In the JS layer I use
let myListener = Plugins.MyPlugin.addListener( 'myEvent' , function( data ) {
console.log( data );
});
In the iOS native layer of the plugin I use
self.notifyListeners( "myEvent" , data: myData )
This all works great, but if the JS layer reloads ( as in live reload ) I need to add the listeners again. Unfortunately reloading the JS layer doesn’t clear the listeners from the native layer and they all continue to fire. So what happens is that listener after listener builds up on the native plugin and they all fire according to the logs. The JS layer thankfully only receives the event from the listener is currently added.
Having searched through Capacitor code I see I have access to the listeners in my plugin.
I can use self.hasListeners( "myEvent" )
and I can also loop through them
guard let listeners = self.getListeners( "myEvent" ) else {
print( "Error fetching listeners" )
call.resolve()
return
}
for listener in listeners {
print( listener )
print( type( of: listener ) )
}
which gives me the following for each listener it finds
<CAPPluginCall: 0x6000013c3090>
CAPPluginCall
So im stuck on how to properly remove each attached listener in the plugin.
I can use self.eventListeners.removeAllObjects()
but I suspect this is wrong and would just cause issues.
Any ideas?