Flawyte Flawyte - 4 months ago 25
Java Question

EventBus: Registering without any @Subscribe annotated method

I have a

BaseFragment
class which registers/unregisters itself to
EventBus
in
onStart()/onStop()
, and several child classes that inherit from it (
FragmentA
,
FragmentB
...). The base class doesn't have any methods annoted with
@Subscribe
, and
FragmentA
neither, but I want it to register anyway in case I add some in the future.

If I register an object that doesn't have any
@Subscribe
annotated method, I except nothing to happen, like when using SquareUp's Otto, but EventBus throws an exception :

org.greenrobot.eventbus.EventBusException: Subscriber class com.company.app.FragmentA and its super classes have no public methods with the @Subscribe annotation


Why throw an exception ? I mean, it doesn't prevent the app to run.

Is the only solution to wrap the
register()/unregister()
calls in
BaseFragment
into an ugly
try ... catch
or is there a cleaner workaround?

Answer

If you want your child fragments to be able to have no @Subscribe method without any exception to be thrown, just put an empty subscriber in the base class :

@Subscribe
public void dummyEvent(SomeClassThatWillNeverBePosted event) {}