问题
I am very new using Android architecture components, so I decided to base my application using GithubBrowserSample to achieve many of my use cases. But i have the problem that i don´t know what is the correct way to share viewmodels between fragments with this approach.
I want to share the view model because i have a fragment with a viewpager with 2 fragments that need to observe data of the parent fragment view model
I used this before to achieve it, based on google's documentation
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")
}
but with the lifecycle-extensions:2.2.0-alpha03 seems to be deprecated
In GithubBrowserSample they have something like this to create an instance of a view model, but with this it seems to be a different instance every time
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val userViewModel: UserViewModel by viewModels {
viewModelFactory
}
And i don't know where to pass the activity scope or if I should pass it.
I tried something like this
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var myViewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myViewModel = activity?.run {
ViewModelProvider(this, viewModelFactory).get(MyViewModel::class.java)
} ?: throw Exception("Invalid Activity")
}
but im getting
kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized
I hope you can help me, i'm a little lost with this, sorry if my english it´s not that good
回答1:
by viewModels()
provides a ViewModel that is scoped to the individual Fragment. There's a separate by activityViewModels() that scopes the ViewModel to your Activity.
However, the direct replacement for ViewModelProviders.of(this)
is simply ViewModelProvider(this)
- you aren't required to switch to by viewModels()
or by activityViewModels()
when using lifecycle-extensions:2.2.0-alpha03
来源:https://stackoverflow.com/questions/57614060/how-to-share-view-models-between-fragments-using-googles-githubbrowsersample-ap