Subscribe Changes in SessionData

Yes, use Spring ApplicationEvents.

Create the publisher bean:

import io.jmix.ui.App;
import io.jmix.ui.AppUI;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CurrentSessionUiEventsPublisher {

    public void publishEvent(ApplicationEvent event) {
        // active app in this session
        App app = App.getInstance();

        // notify all opened web browser tabs
        List<AppUI> appUIs = app.getAppUIs();
        for (AppUI ui : appUIs) {
            if (!ui.isClosing()) {
                // work in context of UI
                ui.accessSynchronously(() -> {
                    ui.getUiEventsMulticaster().multicastEvent(event);
                });
            }
        }
    }
}

Create the event class:

import org.springframework.context.ApplicationEvent;

public class GreetingEvent extends ApplicationEvent {

    private final String greeting;

    public GreetingEvent(Object source, String greeting) {
        super(source);
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting;
    }
}

In a sender screen, publish the event:

@Autowired
private CurrentSessionUiEventsPublisher currentSessionUiEventsPublisher;

@Subscribe("sendEvent")
public void onSendEventClick(Button.ClickEvent event) {
    currentSessionUiEventsPublisher.publishEvent(new GreetingEvent(this, "Hello!"));
}

Subscribe to the event in receiver screens:

@Autowired
private Notifications notifications;

@EventListener
public void onGreeting(GreetingEvent event) {
    notifications.create().withCaption(event.getGreeting()).show();
}

The event will be delivered to receiver screens in all browser tabs of the currently connected user.

See also this message for other options for sending events.

Regards,
Konstantin

2 Likes