Fragment Callbacks vs EventBus in Android

好久不见. 提交于 2019-12-19 10:26:16

问题


I have faced with the problem. My Activity is fragment container, so to communicate between activity and fragments I used common Callback approach. In this case my activity has to implement tons of callback interfaces depending on fragment count.
I don't like to hardcode and unreadable code. In my case my class declaration can take several lines to list all interfaces.
I am trying to get rid of this.

There is another approach is to use EventBus pattern.
In activity

EventBus.getDefault().register(this);

In fragment

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

And handle several event types in activity.

Maybe there will be better to use EventBus here instead default Callback approach ??
Or maybe there is my fault that my activity is holding a lot of fragments (God Object) and it is better to use activities instead Fragment ?

Please suggest which approach is better ?


回答1:


For simple one Activity to one Fragment hierarchy, callback is simplest decision to go. But think about Activity containing a Fragment, and the Fragment contains swipe-able ViewPager, and each tab of ViewPager has Fragments A,B,C.

The Fragment A,B,C will go to long journey to send event to mother Activity, and it can be lost interface connectivity between Activity and children when they are restored during crazy complex Android Activity-Fragment lifecycle dances. In this case, eventbus like otto can be a good choice.

The drawback of event bus approach is, it is hard to maintain where the event is come from. So, keeping a few sender is recommended.




回答2:


Your interface approach is awesome, just keep up with them, and maybe try and slice/make your interface static and add all the little little voids and return methods to that interface so you can just implement one and call the functions.

EventBus? how about LocalBroadcastReceiver ? its a matter of preference and which one you feel will suit you better, after all if you handle 10,000 request and hate having 100 interfaces, you will end up using 1 and nesting 99.

& just forgot, it is better to hold alot Fragment instead of Activity because at the end of the day the Activity lifecycle is pretty hard to maintain second of all you can not really control Activityies well all as compared to Fragments and Fragment is a good slave, serves you better

hope its valuable



来源:https://stackoverflow.com/questions/30553942/fragment-callbacks-vs-eventbus-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!