Use ViewModelFactory inside Fragment

Viewed 2738

I'm trying to share a ViewModel between my activity and my fragment. My ViewModel contains a report, which is a complex object I cannot serialize.

    protected val viewModel: ReportViewModel by lazy {
        val report = ...
        ViewModelProviders.of(this, ReportViewModelFactory(report)).get(ReportViewModel::class.java)
    }

Now I'm trying to access the viewmodel in a fragment, but I don't want to pass all the factory parameters again.

As stated by the ViewModelProvider.get documentation:

Returns an existing ViewModel or creates a new one in the scope

I want to access the ViewModel instance defined in the activity, so I tried the following but it logically crashes as the model doesn't have an empty constructor:

protected val viewModel: ReportViewModel by lazy {
    ViewModelProviders.of(requireActivity()).get(ReportViewModel::class.java)
}

How one should access its "factorysed" ViewModels in a fragment? Should we pass the factory to the fragment?

Thanks!

1 Answers

A little late but I had this question myself. What I found is you can do the following:

In your activity override getDefaultViewModelProviderFactory() like so:

override fun getDefaultViewModelProviderFactory(): ReportViewModelFactory {
    return ReportViewModelFactory(report)
}

now in your fragments you can do

requireActivity().getDefaultViewModelProviderFactory()

to get the factory.

Or simply instantiate your viewModel like:

private val viewModel: ReportViewModel by activityViewModels()
Related