MVVM recyclerview click listener

I do not use data binding nor navigation graph. Single activity app holds Fragment B and has recyclerview in it, I want to navigation in Fragment C while item click in Fragment B recyclerview Item using MVVM. The approach I aware out of the Navigation graph and data binding is making interface and communicate to Activity. Is it the right approach in MVVM?

I am not a GUI architecture expert, and “MVVM” has very blurry definitions IMHO, so I cannot tell you if this is “the right approach in MVVM”. I can tell you that if Fragment B and Fragment C are peers (i.e., both managed by the same parent), that telling the parent to navigate from B to C is normal. And, if that parent is an activity, telling the the activity to navigate from B to C is normal.

The use of interfaces for that communication mostly was to foster reuse, such as making it easier for Fragment B to be hosted by multiple activities.

1 Like

Yes, make sense. I also see different definitions of MVVM and different approaches by industry people. GoogleCodelab also mostly uses a Navigation graph for recyclerview listeners and apart from it, another approach they encourage is Interfaces. So looks like the interface is the only solution for people who don’t like to use the navigation graph.

“Only” is a very strong term.

For example, your activity and Fragment B might share a ViewModel (e.g., via the activityViewModels Kotlin property delegate). Fragment B might then raise an event in that ViewModel (e.g., BroadcastChannel, RxJava PublishSubject) that the activity observes and uses as the signal to perform the navigation.

In my case my activity is only doing a fragment transaction, there is no ViewModel in the activity nor it shared by any other component, Both fragments have separate ViewModel. I host my ViewModel inside fragments.