Start polling and update UI from Event Listener?

Hello,

First off. I am new to Vaadin and this is my first project so I may not being doing things correctly and I am open to suggestions.

I have a drop down box and when I select an item I want to start polling so I can set a loading label visible. When I start the polling from the event listener it doesn’t work. If I move setPollInterval and Thread start outside of the event listener it works. What am I doing wrong and is there a better way to do this?

productCombo.addValueChangeListener(event → {
productSelected = (Product) event.getProperty().getValue();
if (productSelected == null) {
return;
}
// Start Polling
UI.getCurrent().setPollInterval(1000);
new Thread(new Loader()).start();
// This is a long running call. Takes about 20 secs
contentLayout.addComponent(createMemberPanels());
UI.getCurrent().setPollInterval(-1);
});

class Loader implements Runnable {
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}

// Wrap UI updates in access to properly deal with locking
access(new Runnable() {
@Override
public void run() {
loadingLabel.setVisible(true);
}
});
}
}

First, this code here would not do what you’re expecting it to do:

UI.getCurrent().setPollInterval(1000); new Thread(new Loader()).start(); contentLayout.addComponent(createMemberPanels()); UI.getCurrent().setPollInterval(-1); You’ve told a new Thread to start and run your Runnable Loader. Thread.start is a non-blocking call, so Java isn’t going to wait for that Thread to finish its work before moving on to the next lines in your code, which immediately turn off polling.

When the Thread finishes sleeping for 5 seconds, it has no way to tell your client that the change is complete, because polling has already been turned off.

This is not how one would typically use the Vaadin framework with Polling though, rather you would typically leave it at a reasonable default, and you would have some idea of this poll time in mind when writing your server-client interactions.

If you don’t mind me asking, why do feel the need to turn on / off polling mode on the fly?

I added a comment to my original post code. The createMemberPanels() method take about 20 seconds to complete so the Loader() thread should have time to fire and the label should be displayed before the main thread reaches the setPollInterval(-1).

What I am trying to achieve is simple. When the user selects an item from the drop down I want to display a label before calling createMemberPanels() letting them know this call may take some time. Then when the call is complete I want to hide the label. Is there a better way to do this besides polling?

You could try using
@Push


https://vaadin.com/book/-/page/advanced.push.html