haroldadmin / Vector

Kotlin Coroutines based MVI architecture library for Android
https://haroldadmin.github.io/Vector/
Apache License 2.0
193 stars 9 forks source link

What to do about shared viewmodels with assisted injection? #30

Closed vdtyson closed 3 years ago

vdtyson commented 4 years ago

I have a shared viewmodel that I'd like to share in all of my vector fragments. I've tried injecting it like shown in the documentation but I get the error saying that the VectorViewModelFactory needs to be created to get an instance of the ViewModel. Help would be much appreciated.

vdtyson commented 4 years ago

I'm wondering what I should do to instantiate mainSharedViewModel here in particular: https://github.com/vdtyson/StreetEats/blob/feature/firebase_authentication/AndroidStreetEats/app/src/main/java/com/versilistyson/androidstreeteats/presentation/ui/authentication/login/LoginFragment.kt

haroldadmin commented 4 years ago

Hi. I'm glad you're trying out Vector in your app.

The best way to share a ViewModel between multiple fragments is to scope it to their parent activity.

Suppose in your app you have one activity and two fragments, and you want to share a ViewModel between these fragments. To accomplish this, create an instance of your ViewModel in your activity like this:

class MainActivity {
  val mainViewModel: MainViewModel by viewModel()
}

And request the MainViewModel in your fragments like this:

class FragmentOne {
  val mainViewModel: MainViewModel by activityViewModel()
}

class FragmentTwo {
  val mainViewModel: MainViewModel by activityViewModel()
}

When you do this, the mainViewModel parameter in FragmentOne, 'FragmentTwo, andMainActivity` will all refer to the same instance of the ViewModel as in your activity.

For a concrete example, you can checkout my app MoonShot for an example: MainActivity.kt LaunchDetailsFragment.kt

haroldadmin commented 4 years ago

I forgot to add this in the reply, but the MoonShot example also shows you how to set this up with AssistedInject.