Trying to execute some code from another session's controller

Let’s say user1 logs in and opens window1 that is controlled by controller1. We store the reference to controller1 in a singleton available at the application level. User2 logs in and opens the same window1 that is controlled by the same controller1. The two controllers are different instances (and after my understanding, ran by different threads). If user2 does update something, I want to be able to run from user2’s controller some code from user1’s controller.

eg.:

Singleton.getInstance().getUser1Controller().updateUIMethod();

something like this.

Is this possible? If this is, how can I do that?

Thank you,
Alex

Hi,

You can employ Events bean for that. See this demo project: https://github.com/cuba-labs/demo-broadcast-event

There is MessageEventBroadcaster bean that contains subscriptions on GlobalMessageEvent.

Usage example:

public class ExtAppMainWindow extends AppMainWindow {
    @Inject
    private MessageEventBroadcaster broadcaster;
    @Inject
    private BackgroundWorker backgroundWorker;

    // Store reference to field, because broadcaster stores weak references
    private Consumer<GlobalMessageEvent> messageHandler;

    @Override
    public void init(Map<String, Object> params) {
        super.init(params);

        UIAccessor uiAccessor = backgroundWorker.getUIAccessor();
        // save reference to message handler
        messageHandler = event -> uiAccessor.access(() -> {
            showNotification(event.getMessage());
        });

        broadcaster.subscribe(messageHandler);
    }

    // Send event

    @Inject
    private Events events;

    public void onSendBtnClick() {
        events.publish(new GlobalMessageEvent("Demo for all!"));
    }
}

When we click Send button - MessageEventBroadcaster publish event for all user sessions. Thus if some screen subscribed on this event - its code is called.

Also, take a look at the recently published add-on Global Events:

1 Like

From now you can easily solve this task using Global Events Add-on

1 Like