https://kotlinlang.org logo
#android
Title
# android
k

KindRoacher

09/28/2019, 1:55 PM
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

Pablichjenkov

09/28/2019, 4:52 PM
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

trevjones

09/28/2019, 6:00 PM
another option is no implementing the interface on the activity, so the activity “has a” rather than “is a”
k

Kris Wong

09/28/2019, 6:21 PM
prefer "has a". it makes me grimmace when I see activities that implement 20 interfaces
p

Pablichjenkov

09/28/2019, 6:23 PM
Definitely "has a" over "is a". I normally use the term
implement
exchangible. But I meant to say "has a".
k

KindRoacher

09/28/2019, 7:02 PM
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

Pablichjenkov

09/28/2019, 8:06 PM
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

stojan

09/29/2019, 11:36 AM
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

dewildte

09/29/2019, 1:12 PM
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.
2 Views