I'm started to implement MVVM
and I do not know if use the ViewModel
inside my Adapter
is a Good Practice or an AntiPattern.
To give you an example, think about a list of colors and an Image that you will change the background. In that case, I'm observing the selected Color and binding the background color to display in the UI.
But I'm observing the colorSelected in two places:
Fragment
in order to change the background colorAdapter
to display which color is selectedSo, Am I using MVVM
properly when I passing and observing the ViewModel
to the Adapter
?
ViewHolders are managed by RecyclerView adapters by creating the Views and ViewHolders and binding the ViewHolder to an item in the list. Adapters notify the RecyclerView on specific changes to the data. Adapters can also handle interactions with Items such as clicks.
RecyclerView has an Adapter with two very important methods that we implement to bind data: RecyclerView. ViewHolder onCreateViewHolder(ViewGroup parent, int viewType);
I am not sure now if it is good pattern, but there is one problem with this: this way your adapter is tied to your ViewModel meaning you can't reuse it with other ViewModel on another screen. On another hand it is much easier to work without those additional callbacks from recyclerView which makes implementation easier. I guess it is "better" to use callbacks, but "easier" to pass ViewModel (I think CG should deal with it without a problem)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With