简体   繁体   中英

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). I searched for other sources and I'm not sure with whom the data from this viewModel is shared. A simple viewModel class was created with one property:

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

A value was set to viewModel from two locations:

root Activity

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

Fragment A:

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

When the property is accessed from the Activity, I see 6 . When it is accessed by a Fragment B (both Fragments are children of the same activity), I see 9 . That's right? The viewModel used by Activity is visible for another Activity only? Or if the viewModel is used by one Fragment then it is visible only for other Fragments as well? 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). You cannot share a ViewModel between multiple activities unless you make your own ViewModelProvider class.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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