The getUI() becoming empty when reload page

I’ve just been experimenting with Vaadin Flow for a few days and don’t understand Vaadin’s UI mechanism.

I get data from “ConsultantService” using CompletableFuture.supplyAsync().thenAccept();

In the thenAccept() function I code the logic like this

System.out.println("ConsultantList updateUIConsultant running... " + getUI() + " and " + UI.getCurrent());

getUI().ifPresent(ui -> ui.access(() -> {
// Render data to UI here
}));

When the page first renders
ConsultantList updateUIConsultant running… Optional[com.vaadin.flow.component.UI@2cf52f17] and null

After reloading the page
ConsultantList updateUIConsultant running… Optional.empty and null

And I don’t know how to manage the UI or understand how to handle it after reload.

Hope everyone can help me, thanks. :smiling_face_with_three_hearts:

Where did you call it? in the constructor? If yes: change it to beforeEnter or afterNavigation Observer callbacks to ensure the UI is always present.

1 Like

UI.getCurrent() obtains the reference from thread local, which present only in the request thread and hence is always returning null in background thread, i.e. when you call this in then accept of the Future.

getUI() obtains UI reference from the component and is having a value if the component is attached. In long running process it is totally possible that user closes the browser or navigates to other view (does not have patience to wait), hence component is no longer attached. In that case it is correct not to update the view either as it is no longer there.

After reloading the page

See my comment above about closing the browser. Reloading the page does something similar. The current page is discarded, a new UI is created etc. So old one is no longer attached, hence getUI() is not having a value.

2 Likes