If a single fragment needs to communicate with an ...
# android
k
If a single fragment needs to communicate with an activity, do you think use of interfaces make sense? If so, suppose we have 5 interface methods implemented in an activity, that would bloat the activity
p
The problem with an Event Bus solution is that is too wide open. As your App start growing the number of events grow so much that you basically run out of names. Developers need to have discipline on that otherwise the code gets a bit harder to maintain. It is also hard for achieving modularity, now every module in your App could depend on any other Module's event. So extracting a piece of your App to reuse in other projects become cumbersome. For the initial problem you can define a Callback interface in the Fragment class and make the Activity implement it. It creates a coupled dependency between the 2 classes though. If your goal is to share data between them I would do it through Activity ViewModel. Create a viewModel with the activity Scope, this ViewModel will offer a LiveData, coroutine Flow or Rx Flowable pipe of events to any subcriber. Your activity will subscribe to this pipe of events when is created. Then from your fragment send events to the ViewModel and it will propagate them to the Activity. This way you don't have the boilerplate of creating a new Callback interface for each Fragment class you create. When you add a new Fragment class just add more event types in your ViewModel.
đź‘Ť 1
t
another option is no implementing the interface on the activity, so the activity “has a” rather than “is a”
k
prefer "has a". it makes me grimmace when I see activities that implement 20 interfaces
p
Definitely "has a" over "is a". I normally use the term
implement
exchangible. But I meant to say "has a".
k
With my current model, my activity handles 5 interface methods. 3 of them are from a fragment. Only fragment can send data but the activity can not send it. I was hoping for a 'clean' way to interact with activity. I though of Livedata but it seemed to be an overkill
p
Try to minimize code in your Activity/ies. For the sake of reusability is better using fragments. Preferable to write code in a Root Fragment which you can ship to another project. Is easier to integrate in an existing code base a Fragment than an Activity.
s
You only need 1 interface method, which can accept a sealed class as an argument. You can model those 5 different thing as data classes/object that implement the sealed class.
đź‘Ť 1
d
If you need to go the interface route you can use
by
delegation and delegate to another class. this could keep your Activity a bit cleaner.