MVVM架构中View主动向ViewModel请求数据是否符合规范?
Great question—this is a super common point of confusion when you're getting your feet wet with MVVM! Let's break this down clearly.
First, let's recap the core idea of MVVM to set context:
- The View's job is to display data and forward user interactions (like button clicks) to the ViewModel. It should react passively to changes in the ViewModel's state whenever possible.
- The ViewModel holds all the business logic, data state, and handles processing user actions. It never references or depends on the View directly.
Now, looking at your code:
fun onClick(view:View){ showUser(viewModel.getUserDisplayName()) }
This is totally compliant with MVVM—here's why:
- This is a user-initiated action (a button click), not the View polling for data on its own. The View is simply acting as a messenger: it takes the user's input and passes it to the ViewModel, then uses the result to update the UI.
- You're not putting any business logic in the View. The
getUserDisplayName()method should be handling the logic of fetching or computing the user's name (whether that's from a local data store, API, or in-memory state) inside the ViewModel—exactly where that logic belongs.
A quick caveat to keep in mind: If getUserDisplayName() represents a state that can change over time (e.g., the user updates their name), you'd want to use an observable pattern (like LiveData in Android, or StateFlow in Kotlin) so the View can automatically react to those changes without needing to call the method manually. But for a one-time request triggered by user interaction (like showing a user's name when a button is tapped), your current approach is perfectly valid.
The key litmus test for MVVM compliance here is: Is the View handling any logic that should live in the ViewModel? In your case, no—you're just bridging the user's action to the ViewModel and displaying the result. That's exactly what the View is supposed to do.
内容的提问来源于stack exchange,提问作者M-Wajeeh

