Search code examples
javaandroiduser-interfacecallbackevent-bus

Is using an EventBus for simple method calling overkill?


I'm trying to create a UI library that basically holds a lot of methods and actions I typically use when building a layout. One example of such a function is managing the fab clicks. I have one fab in the main activity, and I change its function, icon, and visibility based on which fragment is loaded. I'm currently doing everything with interfaces as you can see here. It all works fine, but the only issue is that I have to make sure other users use activities and fragments that extend my interface.

Example

protected void hideFab() {
    capsuleActivity().getFab().hide();
}

protected CActivityCore capsuleActivity() {
    if (!(getActivity() instanceof CActivityCore)) {
        throw new RuntimeException(s(R.string.capsule_activity_context_error));
    }
    return ((CActivityCore) getActivity());
}

If they don't need the functions for one fragment, they have to override a lot of my methods to make it not do anything. My other option could be to use an EventBus, and to just send various events whenever something is called and resolve it accordingly. That way, it no longer matters if users use my classes or not; if they only want the functions in a few fragments, they can just extend my fragment for those fragments and not worry about the rest.

My question is, would this be a nice and viable way of doing things, or is this moreso overkill as to how EventBuses should be used?

Another function I'm considering is to have the activity send a callback to the current fragment and have it run only if the fragment extends a certain class.

Current implementation:

@SuppressWarnings("unchecked")
protected <T extends Fragment & CFragmentCore> void onCurrentFragment(Class<T> clazz, @NonNull Current<T> callback) {
    Fragment current = getSupportFragmentManager().findFragmentById(getFragmentId());
    if (clazz.isInstance(current.getClass())) {
        callback.onMatch((T) current);
    }
}

But I could also instead use an EventBus with an event containing the class and a callback function.


Solution

  • Using an EventBus is a design choice. It has advantages and disadvantages, which you can easily find on Google.

    There is no such thing as an "overkill" if you are able to simplify your code.

    Apart from that, an EventBus is probably a good idea in your scenario, as it provides an easy way to manage View-Controller communication.