Search code examples
androidotto

How to know a Otto Subscriber is registered


I am using Otto by Square. My subscriber class is registered in the Activity / Fragment onStart and onStop methods.

However sometimes, I get this error

Caused by: java.lang.IllegalArgumentException: Missing event handler for an annotated method. Is class EventListener registered? at com.squareup.otto.Bus.unregister(Bus.java:289)

I am pretty sure my class is registered. Is there a method to know if this class is registered or not ?

// in a Fragment or Activity
@Override
public void onStart() {
    super.onStart();

    Bus bus = new Bus();
    bus.register(eventListener); // register the class where the annotated @Subscribe method is
    bus.isRegistered(); // ??
}

Solution

  • Like @laalto said there is no such method in Bus API. Here is how I implemented the boolean isRegistered

    //  implement as a Singleton class
    public class EventListener {
    
        // necessary to avoid to unregister a non-registered instance . Since EventListener is a Singleton
        private static boolean isRegistered;
    
        public void setIsRegistered(final boolean registered){
            isRegistered = registered;
        }
    
        public boolean isRegistered(){
            return isRegistered;
        }
    
        @Subscribe
        public void onTrackingEvent(final TrackingEvent event) {
            // to do
        }
    }
    

    Now in the Fragment or Activity, register/unregister to the com.squareup.otto.Bus

    // in a Fragment or Activity
    @Override
    public void onStart() {
        super.onStart();
        // eventListener is the class containing the @Subscribe method
        bus.register(eventListener);
        eventListener.setIsRegistered(true);
    }
    
    @Override
    public void onStop() {
        super.onStop();
        if (eventListener.isRegistered()) {
            bus.unregister(eventListener);
            eventListener.setIsRegistered(false);
        }
    }