Fire destroyListener imemdiately after close Session

Viewed 119

I'm working on the session management panel. I want to kill another user`s session by clicking button. I created grid with VaadinSession object and button with VaadinSession.close() functionality but after close() destroy session listener isnt firing immediately and his website isnt reloading. It is fired after some time but when user with closed session clicks on anything in his website then destroyListener is firing sooner. Is there any option to fire DestroyListener immediately after closing session?

1 Answers

VaadinSession.close() just sets a flag stating that the session is going to be closed. The actual cleanup is performed when handling a request from that session. That's why clicking a button triggers the SessionDestroyListener (alternatively, a heartbeat would have the same effect).

With Vaadin 14+, you can force each UI in the closed session to execute a no-operation, so that a server-client rountrip take place.

session.getUIs().stream().forEach(ui->ui.getElement().executeJs("return"));

At that point:

a) the server will realize that the current session has been closed, then the session will be destroyed (and replaced with a new one)

b) the client will reload each browser tab for the new session.

@Push
@Route
public class MainView extends VerticalLayout {

  public MainView() {     
    ApplicationServiceInitListener.sessions.forEach(session->{
      if (session!=VaadinSession.getCurrent()) {
        Button btn = new Button("Close "+session.hashCode());       
        btn.addClickListener(ev->{session.access(()->close(session)); remove(btn);});
        add(btn);
      }});
  }

  private void close(VaadinSession session) {
      session.getUIs().stream().forEach(ui->ui.getElement().executeJs("return"));
      session.close();
  }


}
Related