Reputation: 23483
I am creating a ViewModel
inside the onBindViewHolder
of a recyclerView
; however, despite creating a new instance of the ViewModel
the same ViewModel
is being used. Here is what it looks like:
@Override
public void onBindViewHolder(@NonNull final CatalogViewHolder holder, int position) {
if(componentData != null){
holder.binding.setComponentData(componentData.get(position));
holder.binding.setAdapter(adapter);
CatalogAdapterViewModelFactory factory = new CatalogAdapterViewModelFactory(MyApp.getApplication(), componentData.get(position).getId());
SliderViewModel sliderViewModel = ViewModelProviders.of(fragment, factory).get(SliderViewModel.class);
sliderViewModel.getPayloadListObservable().observe(fragment, new Observer<SliderData>() {
@Override
public void onChanged(SliderData payloads) {
adapter.updateAdapterInfo(payloads.getPayload());
}
});
}
}
How do I create a new instance of ViewModel
in the same fragment/view?
Upvotes: 0
Views: 853
Reputation: 29260
The ViewModel
s are associated with an owner, in this case the Fragment
. As long as you pass the same Fragment
to the factory method, you'll get the same viewmodel.
You should not use a ViewModel
from the arch components for this use, you have to instantiate it manually each time.
Your problem is this line
SliderViewModel sliderViewModel = ViewModelProviders.of(fragment, factory).get(SliderViewModel.class);
You need somethign like this
SliderViewModel sliderViewmodel = new SliderViewModel( /* pass stuff here */)
Upvotes: 2