简体   繁体   中英

android - What is the 1:n relationship between view and viewModel

I know view and viewmodel are 1:n. However, in most examples there was one viewmodel per activity. ex) mainActivity - mainViewModel, userListActivity - userListViewModel

Shouldn't it be like below if it's a 1:n relationship?? ex) mainActivity - viewModel, userListActivity - viewModel

What does 1:n mean? Does it mean n activities in one viewmodel? Does it mean n xml files in one viewmodel?

Yes the common use-case is 1:1 . But theoretically you could have multiple ViewModels serving a view, so that's why the 1:n relation.

In practice this could be useful if you'd like to share a ViewModel between two views for example, or when you have a shared Flow ViewModel

So basically in that flow every View could communicate with two ViewModels : the shared one and one specific for that view:

  • Imagine a SignUp flow, with two screens user credentials (email, password, etc...) and another one with some preferences (like membership, notification, address or other app specific settings)
  • In this case the SharedFlowViewModel could hold all the user information, and at the last screen the Submit will send the request. All other screens with the individual ViewModel s would just handle the individual screen logic: form validation, input enabling/desabling, etc...

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