简体   繁体   English

Android viewModel和Kotlin:与谁共享viewModel数据?

[英]Android viewModel and Kotlin: Who is the viewModel data shared with?

I studied the viewModel class and did a simple test to understand the theory (beginner). 我研究了viewModel类,并做了一个简单的测试来理解该理论(初学者)。 I searched for other sources and I'm not sure with whom the data from this viewModel is shared. 我搜索了其他来源,但不确定与该viewModel的数据共享给谁。 A simple viewModel class was created with one property: 使用一个属性创建了一个简单的viewModel类:

class MyViewModel: ViewModel() {
    var result: Int? = null
}

A value was set to viewModel from two locations: 从两个位置为viewModel设置了一个值:

root Activity 根活动

val model = ViewModelProviders.of(this).get(MyViewModel::class.java)
model.result = 6

Fragment A: 片段A:

val model = ViewModelProviders.of(activity).get(MyViewModel::class.java)
model.result = 9

When the property is accessed from the Activity, I see 6 . 当从Activity中访问属性时, 我看到6 When it is accessed by a Fragment B (both Fragments are children of the same activity), I see 9 . 当通过片段B(两个片段都是相同活动的子代)访问它时, 我看到9 That's right? 那就对了? The viewModel used by Activity is visible for another Activity only? Activity使用的viewModel仅对另一个Activity可见吗? Or if the viewModel is used by one Fragment then it is visible only for other Fragments as well? 还是如果一个片段使用了viewModel,那么它也仅对其他片段可见? If yes, to see one another, do I need to use something like bundle, arguments, intents or something else? 如果是,要互相看到,是否需要使用捆绑,参数,意图或其他东西? I'll be grateful for the help. 我将不胜感激。

A view model that is retrieved by ViewModelProviders.of(activity) is shared only to that activity and its childeren (fragments). ViewModelProviders.of(activity)检索的视图模型仅与该活动及其子项(片段)共享。 You cannot share a ViewModel between multiple activities unless you make your own ViewModelProvider class. 除非您创建自己的ViewModelProvider类,否则不能在多个活动之间共享ViewModel。

If you need to share data between your activities, You should follow the repository pattern and first store your data in a repository (that is bound to the application not activities) and retrieve the data in the other activity from that repository. 如果需要在活动之间共享数据,则应遵循存储库模式,首先将数据存储在存储库中(该存储库绑定到应用程序而不是活动),然后从该存储库中检索其他活动中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM