EventListener stops working on new view instance

We are currently developing a new Jmix app. Currently using Jmix 2.3.3 but we want to update to 2.4.x before release.

We have two views. On ViewA we fire an ApplicationEvent and listen to it on ViewB. Depending on the status of ViewB we navigate to another instance of the same view. In this case it seams that the event listener stops working. Any suggestion?

public class MyCustomEvent extends ApplicationEvent {
    private final UUID entityId;

    public MyCustomEvent(Object source, UUID entityId) {
        super(source);
        this.entityId = entityId;
    }

    public String getEntityId() {
        return entityId;
    }
}

@ViewController("viewA")
@ViewDescriptor("view-a.xml")
public class ViewA extends StandardListView<MyEntity> {

    public void fireEvent(final UUID someId) {
        MyCustomEvent event = new MyCustomEvent(this, someId);
        eventPublisher.publishEvent(event);
    }
}

@ViewController("viewB")
@ViewDescriptor("view-b.xml")
public class ViewB extends StandardDetailsView<MyEntity> {

    @EventListener
    public void onMyCustomEvent(MyCustomEvent event) {
        System.out.println("Received event: " + event.getEntityId());

        if (shouldNavigateToNewInstance()) {
            navigateToNewInstance(event.getEntityId());
        }
    }

    /**
     * Determine if navigation to a new instance is needed
     */
    private boolean shouldNavigateToNewInstance() {
        return true;
    }

    private void navigateToNewInstance(final UUID someId) {
        getScreenNavigators().detailView(this, MyEntity.class)
            .withViewClass(ScreenB.class)
            .editEntity(dataManager.load(MyEntity.class).id(someId).one())
            .navigate();
    }
}

Hello,

thank you for reporting a problem! I created the issue in GitHub: Application event listeners do not work after renavigation to the same view · Issue #3992 · jmix-framework/jmix · GitHub

The problem is that listeners are removed after closing the view. And new listeners for renavigated view are not added.

I think you can use the following workaround:

private boolean reNavigation = false;

@Subscribe
public void onBeforeShow(final BeforeShowEvent event) {
    if (reNavigation) {
        getApplicationContext().getBean(EventListenerDependencyInjector.class)
                .autowire(new ViewAutowireContext(this));
    }
}

@Subscribe
public void onAfterClose(final AfterCloseEvent event) {
    reNavigation = true;
}