Osw*_*llo 1 android mvvm kotlin dagger-2 android-architecture-components
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")
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
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")
}
Run Code Online (Sandbox Code Playgroud)
but im getting
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")
}
Run Code Online (Sandbox Code Playgroud)
希望您能对我有所帮助,我对此有些迷惑,对不起,如果我的英语不好
by viewModels()提供一个范围为单个Fragment的ViewModel。有一个单独的by activityViewModels()范围将ViewModel范围限定到您的Activity。
但是,直接替换ViewModelProviders.of(this)很简单ViewModelProvider(this)-您不需要切换到by viewModels()或by activityViewModels()使用lifecycle-extensions:2.2.0-alpha03
| 归档时间: |
|
| 查看次数: |
208 次 |
| 最近记录: |