2

I have an abstract fragment in Android which I perform the register and unregister method from the otto bus. Also I have a @Subscribe for a method inside this class.

public abstract class MyBaseFrag extends Fragment {

    @Override
    public void onResume() {
        super.onResume();
        bus.register(this);
    }
    // unregister onPause...

    @Subscribe
    public void loadMapOnAnimationEnd(TransitionAnimationEndEvent event) {
        loadMap();
    }
}

I have another fragment which extends from this and is the one it's being executed. I send the event but the method is never called.

public class MyFragment extends MyBaseFrag {
    // my code here..
}

Problem:

I send the event but the method is never called.

Juan Saravia
  • 7,661
  • 6
  • 29
  • 41

2 Answers2

9

I realized that @Subscribe doesn't work in abstract classes but it works in the concrete class.

Just moving the @Subscribe method into MyFragment (not abstract class) it just works:

public abstract class MyBaseFrag extends Fragment {

    @Override
    public void onResume() {
        super.onResume();
        bus.register(this);
    }
    // unregister onPause...
}


public class MyFragment extends MyBaseFrag {
    @Subscribe
    public void loadMapOnAnimationEnd(TransitionAnimationEndEvent event) {
        loadMap();
    }
}

It works!

Juan Saravia
  • 7,661
  • 6
  • 29
  • 41
1

That's a feature - see Subscribing in the documentation:

Registering will only find methods on the immediate class type. Unlike the Guava event bus, Otto will not traverse the class hierarchy and add methods from base classes or interfaces that are annotated. This is an explicit design decision to improve performance of the library as well as keep your code simple and unambiguous.

tynn
  • 38,113
  • 8
  • 108
  • 143