[英]Load ViewModel instance in another activity
When app start I need to download data and populate all viewModels to avoid slowdowns during the app usage. 应用程序启动时,我需要下载数据并填充所有viewModel,以避免在应用程序使用过程中速度变慢。 First activity is: 第一项活动是:
public class MainActivity extends AppCompatActivity {
private MainViewModel mainViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
}
}
I'm thinking to create in the activity above the instance of the other activity's viewModel and pass it through the intent. 我正在考虑在活动中创建另一个活动的viewModel实例的实例,并将其传递给意图。 I'm not sure if is it right to create the instance of a viewModel not in its consistent activity. 我不确定不是在其一致的活动中创建viewModel的实例是否正确。
The
ViewModel
class is designed to store and manage UI-related data in a lifecycle conscious way.ViewModel
类旨在以生命周期感知的方式存储和管理与UI相关的数据。
If you want to share any data between your viewModels, the best idea would be creating a singleton
data source and provide it inside of viewModels, such as SharedPreferences
, sqlite
datase, etc. 如果要在viewModel之间共享任何数据,最好的方法是创建一个singleton
数据源,并将其提供到viewModel内部,例如SharedPreferences
, sqlite
datase等。
If you really need to use a viewModel as your data source you can create a singletone
instance of it by implementing a custom ViewModelFactory
which has been already discussed in this github issue : 如果你真的需要使用视图模型作为数据源,你可以创建一个singletone
通过实现自定义它的实例ViewModelFactory
已在此github上已经被讨论的问题 :
you can use factory to make viewmodel and this factor will return single object of view model.. As: 您可以使用factory来创建viewmodel,并且此因子将返回视图模型的单个对象。
class ViewModelFactory() : ViewModelProvider.Factory {
override fun create(modelClass: Class): T {
if (modelClass.isAssignableFrom(UserProfileViewModel::class.java)) {
val key = "UserProfileViewModel"
if(hashMapViewModel.containsKey(key)) {
return getViewModel(key) as T
} else {
addViewModel(key, UserProfileViewModel())
return getViewModel(key) as T
}
}
throw IllegalArgumentException("Unknown ViewModel class")
}
companion object {
val hashMapViewModel = HashMap<String, ViewModel>()
fun addViewModel(key: String, viewModel: ViewModel) {
hashMapViewModel.put(key, viewModel)
}
fun getViewModel(key: String): ViewModel? {
return hashMapViewModel[key]
}
}
}
In Activity: 活动中:
viewModelFactory = Injection.provideViewModelFactory(this)
// Initialize Product View Model
userViewModel = ViewModelProviders.of(this,viewModelFactory).get(UserProfileViewModel::class.java)
This will provide only single object of UserProfileViewModel which you can share between Activities. 这将仅提供UserProfileViewModel的单个对象,您可以在Activity之间共享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.