Search code examples
vaadinpollingvaadin-flow

Vaadin Flow: Remove PollListener


Is there a possibility to remove a PollListener in Vaadin 14?

UI.getCurrent().addPollListener(pollEvent -> { refresh(); }

I need to start refreshing, but if the Route or UI is changed, the refreshing has to stop.

Is there a "Vaadin possibility" for that, or do I have to build something on my own?

Thank you!


Solution

  • As noted in the docs, in order to disable polling, one should call

    UI.getCurrent().setPollInterval(-1);
    

    In order to ensure that this is called upon navigating away from the view, you can make this call from within a BeforeLeaveObserver. Here is an example:

    public class Foo extends Div
            implements BeforeLeaveObserver {
        @Override
        public void beforeLeave(BeforeLeaveEvent event) {
            UI.getCurrent().setPollInterval(-1);
        }
    
    }
    

    If you want to remove a single poll listener while keeping polling enabled, you can store a reference to the Registration object returned by the addPollListener() method and then call the remove method from the Registration.