Thereβs always need for communication, right π Suppose we have OnboardingActivity that has several OnboardingFragment. Each Fragment has a startButton telling that the onboarding flow has finished, and only the last Fragment shows this button.
Here are several ways you can do that
1. EventBus π
Nearly all articles I found propose this https://github.com/greenrobot/EventBus, but I personally donβt like this idea because components are loosely coupled, every component and broadcast can listen to event from a singleton, which makes it very hard to reason when the project scales
// Listen should return an Observable and not the publisher // Using ofType we filter only events that match that class type fun <T> listen(eventType: Class<T>): Observable<T> = publisher.ofType(eventType) }
This is advised here Communicating with Other Fragments. Basically you define an interface OnboardingFragmentDelegate that whoever conforms to that, can be informed by the Fragment of events. This is similar to Delegate pattern in iOS π
We can learn from Share data between fragments to to communication between Fragment and Activity, by using a shared ViewModel that is scoped to the activity. This is a bit overkill
1 2 3
classOnboardingSharedViewModel: ViewModel() { val finish = MutableLiveData<Unit>() }