Search code examples
javaeventsgwtgwtp

GWTP EventBus on Non-Presenter Class


In my GWTP Application I have a simple Java class, which is not a Presenter, it's just a single class. From this class, I need to fire an event that will be listened from a Presenter class.

GWTP has a single EventBus shared amongst the presenters. The problem is I need to fire the event from the outside class in this EventBus in order for the presenters to be able to listen to it.

I did my research and so far I haven't encountered a way to share GWTP's EventBus with this external class (except from inside any random presenter, which is not correct).

As I see here, the methods of injecting does not work. Any ideias?

I'll share some code if needed. Thanks!

Here is my Class:

public class MyClass {

private static MyClass INSTANCE;

public static MyClass singleton() {

    if (INSTANCE == null) {
        INSTANCE = new MyClass();
    }
    return INSTANCE;
}

private MyClass() {
}
}

And

@Inject EventBus eventBus

does not work. When I call eventBus.fireEvent(), eventBus is undefined.


Solution

  • You should rewrite your class and use Gin to bind MyClass as a Singleton with bind(MyClass.class).in(Singleton.class) and inject MyClass where you need it instead. Your MyClass class could then look like this :

    public class MyClass {
        @Inject
        MyClass(EventBus eventBus) {
            this.eventBus = eventBus;   
        }
    }
    

    If you really want to do your own singleton, then you can also use static injection from a Gin module : requestStaticInjection(MyClass.class).

    public class MyClass {
        @Inject
        private static EventBus eventBus;
        private static MyClass INSTANCE;
    
        public static MyClass singleton() {
            if (INSTANCE == null) {
                INSTANCE = new MyClass();
            }
            return INSTANCE;
        }
    
        private MyClass() {
        }
    }