How to use a ViewModelProvider.Factory when extends from AndroidViewModel

mposadar picture mposadar · Aug 13, 2018 · Viewed 12.6k times · Source

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.

Answer

Andrey K picture Andrey K · Jan 25, 2019

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;
    }
}