Definition

The ViewModel is the translator component in MVVM and MVVM-C patterns. It exposes data streams and state that the View binds to via data binding mechanisms.

flowchart LR
    V[View] <-.->|data binding| VM[ViewModel]
    VM <-->|business data| M[Model]
    
    V -->|commands| VM
    VM -->|observable state| V

Responsibilities

  • State Exposure: Exposes observable properties for View binding
  • Command Handling: Receives and processes user actions from View
  • Data Transformation: Converts Model data for View consumption
  • Business Logic: Contains presentation and UI-related business logic

Key Characteristics

  • Data Binding: View automatically updates when ViewModel state changes
  • No View Reference: ViewModel doesn’t hold reference to View
  • Observable: Properties exposed as streams, state, or published values
  • Testability: Can be tested without UI framework

ViewModel vs Presenter

Unlike Presenters, ViewModels don’t call View methods. They expose state that Views observe via binding. This enables declarative UI frameworks.

Platform Implementations

PlatformBinding Mechanism
Android JetpackLiveData, StateFlow, Compose State
iOS SwiftUI@Published, @State, ObservableObject
ReactuseState, useReducer, Context
VueReactive proxy, ref, computed
WPF/AvaloniaINotifyPropertyChanged, ReactiveUI

Common Patterns

// ViewModel example (pseudo-code)
class TaskViewModel {
  // Observable state
  tasks: ObservableList<Task>
  isLoading: ObservableBoolean
  
  // Commands
  fun loadTasks() { ... }
  fun addTask(title: String) { ... }
  fun deleteTask(id: String) { ... }
}

Comparison with Other Translators

ComponentFocusData Flow
ControllerInput handlingUser → Controller → Model
PresenterView formattingModel → Presenter → View
ViewModelState bindingModel ↔ ViewModel ↔ View