https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
n

nicopasso

08/07/2019, 10:09 AM
We are trying to understand how viewmodels and recyclerviews can work together. In our case we have a custom view, used in an activity, with its own viewmodel. Now this custom view need to be part of the layout of items in a recyclerview. That means each ViewHolder will have a ViewModel attached to it. We think it’s not a good solution but we’re wondering what would it be a way to structure this type of situation. ViewModel attached to the adapter (we think it’s bad)? use DataBinding to connect VH and VM? we don’t have databinding set up in the project though. What do you guys think?
g

gvetri

08/07/2019, 10:21 AM
In the sunflower app (https://github.com/googlesamples/android-sunflower) , the Adapter ViewHolder has a viewModel and this ViewModel sets the data. You can check it out and see if that works for you 😄.
n

nicopasso

08/07/2019, 10:21 AM
uh thanks. I always forget about the sunflower project 🙂
g

gvetri

08/07/2019, 10:22 AM
Don’t worry, I hope that can help you or give you an idea at least.
n

nicopasso

08/07/2019, 10:24 AM
I think the big difference we have compared with this example is that we need livedata to change the VH UI after an API call
and I find odd to use livedata observer inside the viewholder binding method. My concern is mostly related to the Lifecycle observation
how does that work in the context of RecyclerView?
p

pg

08/07/2019, 3:15 PM
Oh my. There is some kind of design flaw. Try to read this article https://proandroiddev.com/adapting-your-recyclerview-the-2019-approach-e47edf2fc4f3 Maybe it will help you resolve your problem
On the other hand, you can check ViewPager class. RecyclerView shouldn't be used to recycle fragments, so this class was created. ViewPager2 looks even more promising. I think you can be inspired by how it works internally. Maybe creating some kind of factory for ViewHolder with it's ViewModel and injecting it externally to adpater isn't that bad idea.
n

nicopasso

08/08/2019, 7:38 AM
I’ve never mentioned fragment inside a RecyclerView. This is not what we have and this is definitely not what we want. Thanks anyway for the link 🙂
p

pg

08/08/2019, 7:59 AM
Yes yes. I has in my mind analogy for complex view with viewmodel and wrote it as example
j

jalexdev

08/31/2019, 1:11 AM
I would recommend having your Activity ViewModel expose the data source (ex; livedata of list of stuff) which your Activity observes and updates an Adapter the activity manages.
7 Views