I am currently migrating an application from Vaadin 7 to Vaadin 23. In the legacy application, there were straightforward methods to add and remove listeners. However, in Vaadin 23, I couldn’t find equivalent methods.
While researching, I came across the following approach for handling event listeners:
I have declared the Registration object globally and attempted to remove the listener where needed. Unfortunately, this method isn’t working as expected.
Could anyone guide me on how to properly remove event listeners in Vaadin 23? Any advice or best practices would be greatly appreciated.
Instead of storing the reference to itemSelectChangeListener so that you can do something like itemSelect.removeValueChangeListener(itemSelectChangeListener);, you store the reference to the registration so that you can later do registration.remove();.
We changed this to make it easier to use lambdas and to chain listeners. With lambdas, the most convenient way is usually to just define the listener inline, i.e. someButton.addClickListener(click -> doSomething()). This pattern means that you don’t have the listener stored in a variable. The other case with chaining is to make it easy to create a listener for a low-level event that delegates to a high-level event listener. Without the registration, you would need some extra bookkeeping to know which low-level listener to remove when a specific high-level listener is removed.
I can understand it if you have some sort of temporary listener, but so far, all my listeners have had the same lifetime as what they listen on.
In that case I assume keeping a reference to the Registration could be counter productive?
Ie, if you don’t keep the Registration reference, everything will be GCd eventually.
If you do keep the Registration reference and forget to call remove, the component and the event will not be GCd.