Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a ViewModelProvider.Factory when extends from AndroidViewModel

Tags:

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.

like image 968
mposadar Avatar asked Aug 13 '18 19:08

mposadar


People also ask

What is ViewModelProvider factory?

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.

How do I use ViewModelProvider on Android?

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.

What is AndroidViewModel?

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.


1 Answers

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;     } } 
like image 170
Andrey K Avatar answered Oct 05 '22 13:10

Andrey K