Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass the ViewModel to a RecyclerView Adapter and observe a LiveData?

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:

  • In the Fragment in order to change the background color
  • In the Adapter to display which color is selected

So, Am I using MVVM properly when I passing and observing the ViewModel to the Adapter?

like image 869
AndroidStorm Avatar asked Jul 15 '18 08:07

AndroidStorm


People also ask

What are differences between RecyclerView adapter and Listadapter?

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.

What RecyclerView adapter method is used for binding data to the view?

RecyclerView has an Adapter with two very important methods that we implement to bind data: RecyclerView. ViewHolder onCreateViewHolder(ViewGroup parent, int viewType);


1 Answers

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)

like image 109
Janusz Hain Avatar answered Oct 05 '22 20:10

Janusz Hain