100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
.NET

The ViewModel in MVVM

How the ViewModel exposes observable state and commands, manages lifecycle, and stays independently testable.

FoundationsIntermediate10 min readJul 10, 2026
Analogies

The ViewModel in MVVM

The ViewModel is the abstraction layer that represents 'what the View needs to display' and 'what the View can do,' expressed entirely as observable properties and invocable commands, with no dependency on any concrete UI control or framework beyond a binding/observation primitive. It pulls raw domain data from the Model via repositories or services, transforms and formats that data for presentation (turning a Decimal into a currency string, or a list of Order objects into a sorted, filtered list of OrderRowViewModel items), and exposes user-triggerable actions as commands the View can bind buttons or gestures to.

🏏

Cricket analogy: A cricket app's match-detail ViewModel takes the raw scorer's feed (Model) and exposes it as ready-to-bind properties like a formatted 'CRR: 6.42' string and a 'canRequestReview' boolean, so the screen never has to compute run rate itself.

Observable Properties

The core mechanism a ViewModel uses to expose state is a framework-specific observable primitive: in .NET, properties raise INotifyPropertyChanged events; in SwiftUI, @Published properties inside an ObservableObject automatically notify subscribers; in Jetpack Compose, mutableStateOf or StateFlow values trigger recomposition when changed; in Angular, RxJS Observables or, more recently, Signals serve the same purpose. Regardless of the specific API, the pattern is identical: the ViewModel mutates a property, the framework's binding layer detects the change, and every View element bound to that property re-renders automatically, without the ViewModel ever calling a method like updateLabel() itself.

🏏

Cricket analogy: Whichever broadcaster's graphics vendor you use — Hawk-Eye, Virtual Eye, or an in-house system — the underlying idea is the same: the scoring engine's internal number changes, and the graphics overlay auto-refreshes, regardless of which specific vendor API triggers it.

kotlin
// Jetpack Compose ViewModel with observable state
class CartViewModel(private val repository: CartRepository) : ViewModel() {
    private val _items = MutableStateFlow<List<CartItemUiState>>(emptyList())
    val items: StateFlow<List<CartItemUiState>> = _items.asStateFlow()

    val total: StateFlow<String> = items.map { list ->
        val sum = list.sumOf { it.price * it.quantity }
        "$%.2f".format(sum)
    }.stateIn(viewModelScope, SharingStarted.Lazily, "$0.00")

    fun removeItem(id: String) {
        viewModelScope.launch {
            repository.removeFromCart(id)
            _items.value = repository.getCartItems().map { it.toUiState() }
        }
    }
}

Commands and User Actions

Alongside observable properties, the ViewModel exposes commands: named, invocable actions that encapsulate what happens when a user interacts with a control, typically implemented as an ICommand object in WPF (with RelayCommand or DelegateCommand as common helper implementations), a plain method in SwiftUI or Compose that the View calls from a button action, or an Output event in a reactive framework. A command's real power is that it can carry its own 'can this currently execute' logic — a submitCommand might report CanExecute as false while a form is invalid — which lets the View disable the corresponding button purely by binding to that property, with zero conditional logic written in the View itself.

🏏

Cricket analogy: A 'Request Review' command in a broadcast app reports as unavailable once a team has used both of its DRS reviews, so the button greys out automatically without the broadcast graphics needing any if-statements of its own.

In WPF, the RelayCommand pattern is the classic way to implement this: a class wrapping an Action (what to do) and a Func<bool> (whether it can currently execute), which the View binds a Button's Command property to, letting the button's enabled state and click behavior both come purely from the ViewModel with no code-behind.

ViewModel Lifecycle and State Management

On mobile platforms, ViewModel lifetime is often intentionally decoupled from a single screen instance: Android's Jetpack ViewModel class is specifically designed to survive configuration changes like screen rotation, so in-flight network calls and loaded data aren't lost and re-fetched every time the device rotates, while the Activity or Fragment (View) is destroyed and recreated underneath it. This means the ViewModel is effectively where you should hold UI-relevant state that needs to outlive a single View instance's lifecycle, such as scroll position, form input the user hasn't submitted yet, or an in-progress upload's percentage, rather than storing that state in the View where it would be lost on recreation.

🏏

Cricket analogy: A cricket app's live-match ViewModel keeps polling and holding the current score even if you rotate your phone to landscape to watch a replay, so the score doesn't reset to zero and re-fetch from scratch on rotation.

Testing the ViewModel

Because the ViewModel depends only on the Model (typically through injected, mockable repository interfaces) and exposes plain observable properties and commands, it can be unit tested by instantiating it directly, injecting a fake or mock repository that returns known data, invoking a command or triggering a property change, and asserting on the resulting property values — all without a device, simulator, or UI test framework. This is where MVVM delivers its biggest practical return on investment: form validation, filtering, sorting, and error-state logic that would otherwise require slow UI tests can instead run in milliseconds as part of a normal unit test suite.

🏏

Cricket analogy: A cricket app's team can unit test 'does the reviewsRemainingText update to 0 of 2 after two failed DRS calls' by feeding a fake match-event stream into the ViewModel, with no actual live match or device needed.

A ViewModel that imports a UI framework type — a UIColor, a Color, a View struct, or a navigation controller reference — has broken MVVM's core contract, sometimes called the 'Massive View Model' problem when it grows to also absorb business logic that belongs in the Model. Keep imports UI-framework-agnostic wherever the platform allows it (e.g., depend only on Combine/ObservableObject in Swift, not SwiftUI itself, when feasible), and push navigation decisions out through an event or coordinator rather than a stored screen reference.

  • The ViewModel exposes 'what the View shows' and 'what the View can do' as observable properties and commands.
  • Observable property primitives vary by platform (INotifyPropertyChanged, @Published, StateFlow, Signals) but all trigger automatic View updates.
  • Commands encapsulate user actions and often carry can-execute logic that lets the View disable controls without its own conditional logic.
  • On mobile, ViewModel lifetime is often decoupled from a single View instance, surviving events like screen rotation.
  • The ViewModel is the right place to hold UI-relevant state that must outlive a single View instance, like unsaved form input.
  • ViewModel logic is unit-testable in isolation by injecting mock repositories and asserting on property values.
  • A ViewModel that imports UI framework types or absorbs Model-level business logic breaks MVVM's separation.

Practice what you learned

Was this page helpful?

Topics covered

#NET#MVVMDesignPatternStudyNotes#MicrosoftTechnologies#TheViewModelInMVVM#ViewModel#MVVM#Observable#Properties#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse