I'm trying to build a library where you can add and remove listeners for events in a pub/sub system, but am running into an issue using method references:
// here, this::printMessage is being passed as an instance of Consumer<String>
pubSub.subscribe(this::printMessage);
pubSub.unsubscribe(this::printMessage);
Internally, calling subscribe()
will add the instance of Consumer<T>
to a Set<Consumer<T>>
, and unsubscribe()
will remove it. This issue arises from the fact that each usage of this::printMessage
here actually causes the compiler to generate a new object reference/instance, so, unsubscribing doesn't actually work.
The workaround so far that I've managed is:
final Consumer<String> consumer = this::printMessage;
pubSub.subscribe(consumer);
pubSub.unsubscribe(consumer);
But, this isn't really ideal. My concern is someone less-experienced using this library may assume that they can use method references directly when subscribing/unsubscribing, when that's not really the case, and worst case, leading to a memory leak.
So the question is, is there some clever way to avoid this or coerce the method reference to always resolve to the same object reference/instance?