[英]As ViewModelProviders.of() is deprecated, how should I create object of ViewModel?
[英]How to share the same ViewModel between Activity and Service when ViewModelProviders.of() is deprecated?
在新的 androidx.lifecycle:lifecycle-extensions:2.2.0 库中,不推荐使用 ViewModelProviders.of()。 它建议我们应该
* @deprecated Use the 'by viewModels()' Kotlin property delegate or
* {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
* passing in the activity.
但是,我想在活动和服务之间共享相同的 ViewModel 实例,我不能使用“by viewModels()”委托。 谁能指出这样做的正确方法是什么?
非常感谢
只需将其替换为
在活动中:
Kotlin: ViewModelProvider(this).get(CustomViewModel::class.java)
Java: ViewModelProvider(this).get(CustomViewModel.class)
服务中:
在服务类中使用关键字new创建一个 viewModel 实例
这些对我有用:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.