Thank you for the article, it was very helpful for me!
If just want to mention I had to remove "?" on line "override fun <T : ViewModel?> create(modelClass: Class<T>): T {" in order to remove a "'create' overrides nothing" error
class MyAndroidViewModelFactory(
private val app: Application,
private val repository: Repository)
: ViewModelProvider.AndroidViewModelFactory(app) {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(
MyAndroidViewModel::class.java)) {
return MyAndroidViewModel(app, repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
Useful info, thanks. But I'm wondering if there's a way to use the view models to share data between an activity and the fragments it contains, or is it only possible between fragments?
I can't find a way to get an activity to be able to set up a view model that the fragments also use if I need a custom factory. They all seem to need the factory to be provided, which then means that the factory has to be provided via some other means. If there are multiple additional arguments then that is slightly better, but otherwise the shared data might just as well be passed more direclty. Even if the factory is passed it's not clear that the same view model would be used rather than the factory being used to construct separate instances.
Native Android Kotlin Developer
I tried to implement your solution but it does not seem to work. Do you have any idea what Im doing wrong?
What I did: Added implementation "androidx.fragment:fragment-ktx:1.3.6"
My Android View Model constructor looks like this:
class MainViewModel(private val app: Application, webApiRepository: IWebApiRepository = WebApiRepository.getInstance(app)) : ViewModelProvider.AndroidViewModelFactory(app)I also added the create function:
override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom( MainViewModel::class.java)) { return MainViewModel(app, webApiRepository) as T } throw IllegalArgumentException("Unknown ViewModel class") }But when I try to use by activityViewModels or viewModels it does not work:
(Remove the two empty spaces) https:// cdn.hashnode .com/res/hashnode/image/upload/v1657015361719/7gYkfO5k8.png
I need to use activityViewModel in order to get a shared ViewModel across fragments. Thanks