I want to send an extra parameter to my ViewModel, but this extends from AndroidViewModel. How can I add this parameter to the ViewModelFactory class ?
ViewModel
class ProjectViewModel(application: Application) : AndroidViewModel(application) { // need a param for project id... }
ViewModelFactory
class ProjectViewModelFactory(val projectId: Int): ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { // need to send this... return ProjectViewModel(projectId) as T } }
Note: I notice that in the documentation its says: AndroidViewModel Subclasses must have a constructor which accepts Application as the only parameter.
So I don't know if it is posible (or good) to do what I'm trying to do.
androidx.lifecycle.ViewModelProvider.Factory that can create ViewModels accessing and contributing to a saved state via SavedStateHandle received in a constructor. ViewModelProvider.NewInstanceFactory. Simple factory, which calls empty constructor on the give class. Known indirect subclasses.
If your ViewModel has dependencies or arguments and you want to create your ViewModel instance, then you should create your custom ViewModelProvider. Factory and pass the dependency or arguments through the ViewModel constructor and give a value to the ViewModelProvider. Factory instance.
The AndroidViewModel class is a subclass of ViewModel and similar to them, they are designed to store and manage UI-related data are responsible to prepare & provide data for UI and automatically allow data to survive configuration change.
Get ViewModel:
viewModel = ViewModelProviders.of(this, new BListFactory(getActivity().getApplication(), 1)) .get(BListViewModel.class);
Factory:
class BListFactory extends ViewModelProvider.NewInstanceFactory { @NonNull private final Application application; private final long id; public BListFactory(@NonNull Application application, long id) { this.application = application; this.id = id; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (modelClass == BListViewModel.class) { return (T) new BListViewModel(application, id); } return null; } }
AndroidViewModel:
public class BListViewModel extends AndroidViewModel { private final long id; public BListViewModel(@NonNull Application application, final long id) { super(application); this.id = id; } }
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