Fragment rejection versus EventBus on Android

I am facing a problem. Mine Activity

is a container of fragments, so I used a generic approach for communication between activity and fragments Callback

. In this case, my activity has to implement many callback interfaces depending on the number of fragments.
I don't like hard code and unreadable code. In my case, a class declaration can take multiple lines to display all interfaces.
I am trying to get rid of this.

Another approach is to use a template EventBus

.
In activity

EventBus.getDefault().register(this);

      

In the fragment

EventBus.getDetault().post(new MyEvent(description));

      

And handle several kinds of events in the activity.

Maybe it would be better to use EventBus instead of the standard callback approach?
Or maybe it’s my fault that my activity contains many Fragments (God Object) and it is better to use Actions instead of Fragment?

Please tell me which approach is better?

+3


source to share


2 answers


For simple work with one chunk hierarchy, callback is the simplest solution. But think of an Activity containing a Fragment and a Fragment contains scipe-able ViewPager

and each ViewPager has Fragments A, B, C.

Fragment A, B, C will go on a long journey to send an event to the Matter action, and the interface interaction between Activity and children may be lost as they rebuild during the crazy complex dance life cycles of Android Fragment . In this case eventbus like otto might be a good choice.



The downside to the event bus approach is that it is difficult to maintain where the event originates from. Therefore, it is recommended that you keep multiple senders.

+3


source


Your approach interface

is awesome, just go ahead with them, and maybe try to slice / make your interface

static and add all the little ones void

and little ones return method

to that interface so you can just implement one and call functions.

EventBus

? how about LocalBroadcastReceiver

? it is a matter of preference and which you think will suit you better, because if you handle 10,000 requests and hate with 100 interface

s, you end up using 1 and invest 99.



& just forgot, it's better to hold alot Fragment

instead Activity

, because at the end of the day the lifecycle is Activity

quite difficult to maintain secondly, you can't really control Activity

before Fragment

and Fragment

- good slave, you better

hope its valuable

+1


source







All Articles