Search code examples
eclipse-rcpe4application-shutdown

Send close message around application


I have a Eclipse E4 application with multiple connections to different servers. Now when opening a MPart the part will call the server to receive his data. Also when the MPart is closed the client send the close to the server so that the client knows that the client does not need to have the updated data.

Now I need to find a way to let the MParts know that the client is shutting down. So that they do not send any messages to the server. This will speedup the shutdown of the client.

How can I send the shutdown command to the Mpart when the user clicked the close button?


Solution

  • Use the event broker to send a message to the parts.

    In the shutdown code send an event:

    @Inject
    IEventBroker eventBroker;
    
    eventBroker.send("my/topic/shutdown", data);
    

    Where data is any data you want to associate with the shudown event.

    "my/topic/shutdown" is just a unique id for the event.

    Use the send method to send the event synchronously, use post to send asynchronously.

    Each part can subscribe to the event with:

    @Inject
    @Optional
    public void shutdown(@EventTopic("my/topic/shutdown") Event event)
    {
      ....
    }
    

    Event is org.osgi.service.event.Event

    You can also use @UIEventTopic if you want the method to be guaranteed to run in the UI thread.

    To handle a click on the application 'close' button you need to put an implementation of org.eclipse.e4.ui.workbench.modeling.IWindowCloseHandler in to the Eclipse Context of the the main window. You can do this in your life cycle class (if you have one). The application startup complete event is suitable for this:

    @Optional
    @Inject
    public void appStartupComplete(@UIEventTopic(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE) Event event, MApplication app, EModelService modelService)
    {
      MWindow window = (MWindow)modelService.find("window id", app);
    
      IEclipseContext windowContext = window.getContext();
    
      windowContext.set(IWindowCloseHandler.class, ContextInjectionFactory.make(AppCloseHandler.class, windowContext));