viewmodel
viewmodel em 30 segundos
- A viewmodel is a mediator in software architecture that prepares and manages data specifically for a user interface screen, ensuring a clean separation of concerns.
- It acts as the 'source of truth' for the UI state, handling logic like data formatting, validation, and user interaction processing without direct UI references.
- Commonly used in the MVVM (Model-View-ViewModel) pattern, it helps developers create apps that are more modular, easier to test, and resilient to lifecycle changes.
- By decoupling the UI from the business logic, viewmodels allow designers and developers to work independently and improve the overall maintainability of large codebases.
In the specialized world of software engineering, specifically within the realm of user interface (UI) design patterns, a viewmodel is a critical architectural component. It serves as a specialized mediator or a 'bridge' that sits between the raw data of an application (the Model) and the visual elements the user interacts with (the View). The term is most famously associated with the Model-View-ViewModel (MVVM) pattern, which was originally introduced by Microsoft architects Ken Cooper and Ted Peters to simplify the event-driven programming of user interfaces. When developers use a viewmodel, they are essentially creating a representation of the data that is specifically tailored for the screen. Unlike a standard data model, which might contain complex database relationships or business logic that the user never needs to see, a viewmodel filters, formats, and prepares that data so it can be easily 'bound' to the UI. This separation of concerns is vital for modern application development because it allows designers to work on the visual layout while developers focus on the underlying logic without constantly stepping on each other's toes.
- The Mediator Role
- The viewmodel acts as a translator. It takes complex data from the backend and converts it into simple properties like strings or booleans that the UI can display directly without further calculation.
By moving the formatting logic into the viewmodel, we ensured that the view remains 'dumb' and only focuses on rendering pixels.
People use the term 'viewmodel' most frequently during architectural discussions, code reviews, and technical planning sessions. If you are building a mobile app for Android using Jetpack Compose or an iOS app using SwiftUI, the viewmodel is likely the heart of your data flow. It manages the 'state' of the screen—for example, whether a loading spinner should be visible, whether an error message should be shown, or what text should appear in a search bar. Because the viewmodel does not have a direct reference to the UI components (like a specific button or a text field), it is highly testable. Engineers can write automated tests to verify that the viewmodel behaves correctly under different conditions without ever needing to launch the actual app on a device. This makes the development cycle faster and the resulting software much more reliable.
- State Management
- The viewmodel is responsible for holding the 'truth' of what is currently happening on the screen, ensuring that even if the screen rotates or changes size, the data remains intact.
We need to update the viewmodel to handle the new user permissions before we update the UI layout.
In a professional setting, mentioning a viewmodel implies a certain level of architectural maturity. It suggests that the team is following the principle of 'Separation of Powers,' where the UI is decoupled from the business logic. This is particularly important in large-scale enterprise applications where multiple developers are working on the same codebase. By standardizing on the use of viewmodels, a team creates a predictable structure where everyone knows exactly where the logic for a specific screen resides. It prevents the 'Massive View Controller' problem, where a single file becomes thousands of lines long and impossible to maintain. Instead, the viewmodel keeps things modular, clean, and organized.
The viewmodel exposes a stream of data that the view observes and reacts to automatically.
- Data Binding
- This is the process where the viewmodel and the view are linked so that changes in one are automatically reflected in the other without manual intervention.
Our viewmodel currently handles too many responsibilities; we should split it into smaller, more focused components.
If the API returns a null value, the viewmodel should provide a default string to avoid crashing the view.
Using the word 'viewmodel' correctly requires an understanding of its role as a noun representing a software object. It is almost always used in the context of development, architecture, or technical documentation. Because it is a compound word derived from 'View' and 'Model,' it is frequently capitalized as 'ViewModel' in code, but in general technical writing, it can be treated as a standard noun. You will often see it paired with verbs like 'instantiate,' 'bind,' 'observe,' 'inject,' and 'test.' For example, a developer might say, 'I need to instantiate the viewmodel before the fragment is created.' This indicates the lifecycle management of the object. Another common usage involves the flow of data: 'The viewmodel observes the repository for changes and then updates the UI state.' Here, the viewmodel is the active agent managing data streams.
- Describing Lifecycle
- 'The viewmodel survives configuration changes, ensuring that the user's input isn't lost when the phone rotates.'
Always ensure that your viewmodel does not hold a reference to a Context, as this can lead to memory leaks.
In a team environment, you might use 'viewmodel' to describe the scope of a feature. 'We should add a new property to the viewmodel to handle the toggle state of the dark mode switch.' This sentence shows the viewmodel as a container for UI-related logic. It is also common to use it when discussing testing strategies: 'Unit testing the viewmodel is much easier than testing the activity because it has no dependencies on the Android framework.' This highlights the architectural benefit of the component. Furthermore, when troubleshooting, a developer might remark, 'The bug isn't in the UI; the viewmodel is providing the wrong data to the observer.' This pinpointing of responsibility is a key reason why the term is so prevalent in modern software engineering discourse.
- Discussing Data Flow
- 'The viewmodel transforms the raw integer from the database into a formatted currency string for the user interface.'
Is the viewmodel responsible for navigation logic, or should that be handled by a separate coordinator?
When writing technical documentation or tutorials, the word is used to guide the reader through the structure of an app. 'In this section, we will create a viewmodel that fetches a list of users from a remote API.' This usage establishes the viewmodel as a functional unit of work. It can also be used as an adjective in some contexts, such as 'viewmodel-driven architecture' or 'viewmodel-first navigation,' though these are less common than its use as a noun. In senior-level discussions, you might hear it used to critique code: 'This viewmodel is becoming a god-object; we need to refactor it.' This indicates that the viewmodel has taken on too many responsibilities, violating the single responsibility principle. Overall, the word is indispensable for anyone describing how data moves from a database to a human eye.
The viewmodel uses a 'StateFlow' to emit updates to the UI whenever the underlying data changes.
- Refactoring Context
- 'We should move this validation logic from the activity into the viewmodel to make it more reusable and testable.'
Each screen in our application is backed by its own dedicated viewmodel to ensure strict separation of concerns.
The viewmodel acts as a buffer, preventing the UI from being overwhelmed by rapid data updates from the network.
The word 'viewmodel' is a staple of the professional software developer's vocabulary. You will hear it most frequently in office environments where mobile or desktop applications are being built. During a morning 'stand-up' meeting, a developer might say, 'I'm finishing up the viewmodel for the login screen today.' This tells the team that the logic for handling user input, validation, and communication with the authentication service is being finalized. It is also a very common term in technical interviews. A candidate might be asked, 'How do you handle state management in your apps?' and they would likely respond by explaining how they use viewmodels to keep the UI in sync with the data. In this context, the word acts as a signal of professional competence and familiarity with industry-standard design patterns.
- In Code Reviews
- 'You've put too much business logic in this viewmodel; some of this should probably be moved to a UseCase or Repository.'
During the architecture meeting, the lead engineer insisted on using a shared viewmodel for the multi-step registration flow.
Beyond the office, you will find 'viewmodel' all over the internet in developer communities. On sites like Stack Overflow, thousands of questions are tagged with 'viewmodel,' ranging from 'how to share a viewmodel between fragments' to 'why is my viewmodel not updating the UI?' It is a central topic in online tutorials on YouTube, Udemy, and Coursera, especially those focusing on Android development with Kotlin or Windows development with C# and WPF. Technical bloggers and 'thought leaders' in the tech space frequently write articles comparing the 'ViewModel' approach to other patterns like 'MVI' (Model-View-Intent) or 'Redux.' In these discussions, the viewmodel is often portrayed as the reliable, standard way to build apps, even as newer, more experimental patterns emerge.
- At Tech Conferences
- 'The speaker at Google I/O explained how the new navigation component integrates seamlessly with the viewmodel lifecycle.'
I read a blog post about using the viewmodel pattern in React to manage complex form states.
You will also encounter the term in official documentation from major tech companies. Microsoft's documentation for .NET and WPF is filled with references to the ViewModel as part of the MVVM pattern. Similarly, Google's Android Developer documentation has an entire section dedicated to the 'ViewModel' class, which they provide as part of their 'Architecture Components' library. In these documents, the word is used with high precision to describe a specific class that developers should inherit from. Even in the world of game development, specifically when using engines like Unity with certain UI frameworks, the concept of a viewmodel is used to separate the game's internal logic from the head-up display (HUD) that the player sees. Wherever there is a need to separate 'how things look' from 'how things work,' you will hear the word 'viewmodel.'
The documentation states that the viewmodel should never contain references to Views or any class that may hold a reference to the Activity context.
- In Job Descriptions
- 'The ideal candidate will have extensive experience with the MVVM pattern and a deep understanding of viewmodel implementation.'
We discussed whether the viewmodel should be responsible for triggering the navigation to the next screen.
The viewmodel is the perfect place to consolidate all the logic for your screen's UI state.
One of the most frequent mistakes developers make when working with a viewmodel is violating the principle of separation of concerns by including UI-specific code within it. A viewmodel should never know about the specific buttons, text views, or layouts used in the View. For instance, importing 'android.widget.Button' into a viewmodel is a major 'code smell.' This mistake makes the viewmodel impossible to unit test without a device and ties it too closely to a specific UI implementation. If the UI changes from a button to a clickable image, the viewmodel shouldn't have to change. Another common error is passing a 'Context' (in Android) or a 'View' reference into the viewmodel. This almost always leads to memory leaks because the viewmodel often lives longer than the View it serves. When the View is destroyed (like when a user hits the back button), the viewmodel might still be holding onto it, preventing the system from reclaiming that memory.
- The 'Fat' ViewModel
- This happens when a developer puts all the application's business logic, networking code, and database queries directly inside the viewmodel, making it huge and hard to manage.
Don't let your viewmodel become a 'God Object' that tries to do everything in your app.
Another mistake is failing to handle the lifecycle of the viewmodel correctly. In some frameworks, viewmodels are designed to survive configuration changes (like screen rotation), but they are not meant to last forever. Developers sometimes forget to clear observers or cancel background tasks when the viewmodel is finally cleared, which can lead to background processes running indefinitely and wasting battery or data. Additionally, some developers use the viewmodel as a simple data holder without any logic. While not technically 'wrong,' it misses the point of the pattern. If a viewmodel only contains a single string that is passed directly from the Model to the View without any transformation, it might be unnecessary overhead. The goal is to have the viewmodel provide 'UI State'—a holistic view of what the screen should look like—rather than just being a mirror of the database.
- Logic Misplacement
- Putting complex business rules (like how to calculate interest on a loan) in the viewmodel instead of the Model or a Domain layer.
If you find yourself writing 'if (view.isVisible)' inside your viewmodel, you are doing it wrong.
Finally, a subtle but impactful mistake is over-complicating the communication between the viewmodel and the View. Using complex custom interfaces or callbacks when a simple 'Observable' or 'StateFlow' would suffice can make the code much harder to read. Conversely, some developers try to share a single viewmodel across too many different screens. While sharing a viewmodel can be useful for passing data between related fragments, doing it excessively creates tight coupling between screens that should be independent. If you change the viewmodel for one screen, you might accidentally break three other screens that you didn't realize were using it. The best practice is generally to have one viewmodel per screen, or a very clearly defined 'shared' viewmodel for a specific, limited flow of screens.
The viewmodel should expose data, not tell the view what to do; the view decides how to show that data.
- Testing Neglect
- Since viewmodels are designed to be testable, not writing unit tests for them is a wasted opportunity to ensure app stability.
A common pitfall is forgetting to handle the 'Error State' in the viewmodel, leaving the user with a blank screen if the network fails.
By avoiding these common viewmodel mistakes, you can build apps that are easier to maintain and much less prone to bugs.
While 'viewmodel' is the dominant term in the MVVM pattern, there are several other components in different architectural patterns that serve similar purposes. Understanding these alternatives helps clarify exactly what a viewmodel is and isn't. The most common alternative is the 'Controller' from the Model-View-Controller (MVC) pattern. In MVC, the Controller is responsible for handling user input and updating the Model, but it often has a more direct relationship with the View than a viewmodel does. In many web frameworks, the Controller is the entry point for a request, whereas a viewmodel is more of a state-holder for a specific piece of UI. Another close relative is the 'Presenter' from the Model-View-Presenter (MVP) pattern. A Presenter is very similar to a viewmodel, but it usually holds a direct reference to an interface implemented by the View. This means the Presenter 'tells' the View what to do (e.g., 'view.showLoading()'), while a viewmodel simply 'exposes' a state (e.g., 'isLoading = true') that the View chooses to react to.
- ViewModel vs. Controller
- A Controller handles the 'how' of user interaction, while a ViewModel focuses on the 'what' of the UI state.
While MVC uses a controller, MVVM relies on the viewmodel to decouple the logic from the layout.
In more modern, functional-reactive architectures, you might encounter terms like 'Store' or 'State.' In the Redux pattern, a 'Store' holds the entire application's state in a single place. While a viewmodel is usually scoped to a single screen, a Redux Store is global. However, both serve the purpose of being the 'source of truth' for the UI. In the Model-View-Intent (MVI) pattern, the equivalent of a viewmodel might be called a 'State Producer' or simply a 'Reducer.' These components take user 'Intents' and produce a new 'State' object. The viewmodel is essentially a more object-oriented way of achieving this same goal. In some smaller applications or simpler frameworks, people might just use a 'Data Transfer Object' (DTO) or a 'Value Object' to pass data to the view, but these lack the logic-handling and lifecycle-awareness that define a true viewmodel.
- ViewModel vs. Presenter
- Presenters are typically one-to-one with a View and use interfaces; ViewModels are often many-to-one and use data binding.
The transition from MVP to MVVM often involves replacing the presenter with a viewmodel to take advantage of reactive programming.
Another term you might hear is 'Binder.' In some older implementations of MVVM, the Binder was a separate component that linked the View and the ViewModel. Today, the 'binding' is usually handled by the framework itself (like Android Data Binding or SwiftUI's @Published properties), so the term 'Binder' has fallen out of common use, but the concept remains central to how a viewmodel works. Finally, in the context of clean architecture, a viewmodel is often seen as part of the 'Interface Adapters' layer. It adapts the data from the 'Use Cases' (business logic) into a format that the 'Frameworks and Drivers' layer (the UI) can understand. Whether you call it a viewmodel, a presenter, or a state-holder, the fundamental goal remains the same: making the UI code cleaner, more testable, and easier to change over time.
In React development, 'Custom Hooks' often serve the exact same purpose as a viewmodel by encapsulating logic and state.
- ViewModel vs. State Holder
- A state holder is a generic term; a ViewModel is a specific type of state holder that is aware of the UI lifecycle.
Choosing between a viewmodel and a simple controller depends on the complexity of your UI and the need for unit testing.
The viewmodel is the most popular choice for modern Android development because of its robust lifecycle management.
How Formal Is It?
Curiosidade
The MVVM pattern and the term 'ViewModel' were actually inspired by the 'Presentation Model' pattern described by Martin Fowler, but Gossman simplified it for use with XAML-based UI frameworks.
Guia de pronúncia
- Pronouncing it as three separate words: 'view-mo-del'. It should flow as a single compound noun.
- Putting the stress on 'model' instead of 'view'.
- Confusing the pronunciation with 'voodoo' (rare but happens with non-native speakers).
Nível de dificuldade
Requires understanding of software architecture and technical jargon.
Correctly spelling and using it in a technical context requires specific knowledge.
Pronunciation is straightforward once you know it's a compound word.
Can be easily confused with 'Model' or 'View' in fast-paced technical discussions.
O que aprender depois
Pré-requisitos
Aprenda a seguir
Avançado
Gramática essencial
Compound Nouns
ViewModel is a compound noun formed from 'View' and 'Model'.
Countable Nouns
We are using three different viewmodels for this feature.
Technical Capitalization
In code, it is 'ViewModel', but in prose, it can be 'viewmodel'.
Possessive Technical Terms
The viewmodel's responsibility is to manage state.
Gerunds as Subjects in Tech
Implementing a viewmodel improves code quality.
Exemplos por nível
The viewmodel helps the screen show the name.
Le viewmodel aide l'écran à afficher le nom.
Simple subject-verb-object structure.
Put the data in the viewmodel.
Mettez les données dans le viewmodel.
Imperative sentence.
Is the viewmodel ready?
Le viewmodel est-il prêt ?
Basic question form.
The viewmodel has the sun icon.
Le viewmodel contient l'icône du soleil.
Present tense with 'has'.
I like this viewmodel.
J'aime ce viewmodel.
Subject-verb-object.
The viewmodel is small.
Le viewmodel est petit.
Using 'is' with an adjective.
Look at the viewmodel.
Regardez le viewmodel.
Imperative.
The viewmodel changes the color.
Le viewmodel change la couleur.
Third person singular present.
The viewmodel gets the list of friends.
Le viewmodel récupère la liste d'amis.
Present tense.
You should use a viewmodel for this screen.
Vous devriez utiliser un viewmodel pour cet écran.
Using the modal 'should'.
The viewmodel keeps the data safe.
Le viewmodel garde les données en sécurité.
Third person singular.
We are updating the viewmodel now.
Nous mettons à jour le viewmodel maintenant.
Present continuous.
Does the viewmodel have the new price?
Le viewmodel a-t-il le nouveau prix ?
Question with 'does'.
The viewmodel is better than the old way.
Le viewmodel est meilleur que l'ancienne méthode.
Comparative adjective.
I created a viewmodel for the login page.
J'ai créé un viewmodel pour la page de connexion.
Past simple.
The viewmodel tells the view what to show.
Le viewmodel dit à la vue quoi afficher.
Complex object 'what to show'.
The viewmodel handles the logic for the shopping cart.
Le viewmodel gère la logique du panier d'achat.
Focus on 'handles' as a functional verb.
If the user clicks delete, the viewmodel removes the item.
Si l'utilisateur clique sur supprimer, le viewmodel supprime l'article.
First conditional structure.
We use data binding to connect the viewmodel to the UI.
Nous utilisons la liaison de données pour connecter le viewmodel à l'interface utilisateur.
Infinitive of purpose 'to connect'.
The viewmodel doesn't know about the specific buttons.
Le viewmodel ne connaît pas les boutons spécifiques.
Negative present simple.
Testing the viewmodel is much faster than testing the whole app.
Tester le viewmodel est beaucoup plus rapide que de tester toute l'application.
Gerund as a subject.
The viewmodel was designed to survive screen rotations.
Le viewmodel a été conçu pour survivre aux rotations d'écran.
Passive voice.
Can you check if the viewmodel is emitting the correct state?
Pouvez-vous vérifier si le viewmodel émet le bon état ?
Indirect question with 'if'.
Each screen in our app has its own viewmodel.
Chaque écran de notre application a son propre viewmodel.
Use of 'each' and 'its own'.
The viewmodel serves as an intermediary between the repository and the UI.
Le viewmodel sert d'intermédiaire entre le référentiel et l'interface utilisateur.
Formal verb 'serves as'.
By observing the viewmodel, the fragment can react to data changes automatically.
En observant le viewmodel, le fragment peut réagir automatiquement aux changements de données.
Gerund phrase 'By observing'.
It is crucial that the viewmodel does not hold a reference to the activity context.
Il est crucial que le viewmodel ne détienne pas de référence au contexte de l'activité.
Subjunctive-like structure 'It is crucial that'.
The viewmodel transforms raw data into a displayable format for the user.
Le viewmodel transforme les données brutes en un format affichable pour l'utilisateur.
Precise technical vocabulary.
We should refactor this logic into the viewmodel to improve testability.
Nous devrions refactoriser cette logique dans le viewmodel pour améliorer la testabilité.
Modal 'should' for recommendation.
The viewmodel's primary responsibility is managing the UI state.
La responsabilité principale du viewmodel est de gérer l'état de l'interface utilisateur.
Possessive form.
When the viewmodel is cleared, all background tasks are cancelled.
Lorsque le viewmodel est effacé, toutes les tâches en arrière-plan sont annulées.
Passive voice in a temporal clause.
The viewmodel exposes a LiveData object that the view subscribes to.
Le viewmodel expose un objet LiveData auquel la vue s'abonne.
Relative clause with 'that'.
The viewmodel encapsulates the presentation logic, ensuring a clean separation from the domain layer.
Le viewmodel encapsule la logique de présentation, assurant une séparation nette de la couche de domaine.
Use of 'encapsulates' and participial phrase 'ensuring'.
Leveraging a viewmodel allows us to maintain a stateless view that merely reflects the current UI state.
L'exploitation d'un viewmodel nous permet de maintenir une vue sans état qui reflète simplement l'état actuel de l'interface utilisateur.
Gerund 'Leveraging' as a subject.
The viewmodel acts as an abstraction of the view, exposing only the necessary data and commands.
Le viewmodel agit comme une abstraction de la vue, n'exposant que les données et commandes nécessaires.
Appositive phrase 'exposing only...'.
Any business logic found in the viewmodel should be moved to a use case to adhere to clean architecture principles.
Toute logique métier trouvée dans le viewmodel devrait être déplacée vers un cas d'utilisation pour adhérer aux principes de l'architecture propre.
Passive voice with 'should be moved'.
The viewmodel facilitates unit testing by allowing developers to verify UI logic without inflating the layout.
Le viewmodel facilite les tests unitaires en permettant aux développeurs de vérifier la logique de l'interface utilisateur sans gonfler la mise en page.
Gerund 'inflating' in a prepositional phrase.
Using a shared viewmodel is an effective strategy for coordinating state between multiple fragments in a single activity.
L'utilisation d'un viewmodel partagé est une stratégie efficace pour coordonner l'état entre plusieurs fragments dans une seule activité.
Complex subject phrase.
The viewmodel should remain agnostic of the specific UI framework being utilized.
Le viewmodel doit rester agnostique vis-à-vis du framework d'interface utilisateur spécifique utilisé.
Use of the technical term 'agnostic'.
We observed a significant reduction in boilerplate code after implementing the viewmodel pattern.
Nous avons observé une réduction significative du code répétitif après avoir implémenté le modèle viewmodel.
Prepositional phrase 'after implementing'.
The viewmodel orchestrates the flow of data, ensuring that the view remains a passive recipient of state updates.
Le viewmodel orchestre le flux de données, garantissant que la vue reste un récepteur passif des mises à jour d'état.
Advanced verb 'orchestrates' and precise terminology.
By centralizing state management within the viewmodel, we mitigate the risks associated with inconsistent UI representations.
En centralisant la gestion de l'état au sein du viewmodel, nous atténuons les risques associés aux représentations incohérentes de l'interface utilisateur.
Gerund phrase 'By centralizing' and 'mitigate'.
The viewmodel's lifecycle is decoupled from the view's ephemeral nature, providing a robust mechanism for state persistence.
Le cycle de vie du viewmodel est découplé de la nature éphémère de la vue, fournissant un mécanisme robuste pour la persistance de l'état.
Use of 'ephemeral' and 'decoupled'.
A common architectural pitfall involves the leakage of domain-specific concerns into the viewmodel's implementation.
Un piège architectural courant implique la fuite de préoccupations spécifiques au domaine dans l'implémentation du viewmodel.
Complex noun phrase as subject.
The viewmodel exposes an immutable stream of UI states, adhering to the principles of unidirectional data flow.
Le viewmodel expose un flux immuable d'états d'interface utilisateur, adhérant aux principes du flux de données unidirectionnel.
Participial phrase 'adhering to'.
Sophisticated viewmodels leverage dependency injection to maintain a clear separation from data source implementations.
Les viewmodels sophistiqués exploitent l'injection de dépendances pour maintenir une séparation claire des implémentations de sources de données.
Use of 'leverage' and 'dependency injection'.
The viewmodel serves as a crucial abstraction that facilitates the parallel development of UI and business logic.
Le viewmodel sert d'abstraction cruciale qui facilite le développement parallèle de l'interface utilisateur et de la logique métier.
Relative clause with 'that'.
We must ensure that the viewmodel's complexity does not escalate to the point where it becomes a 'God Object'.
Nous devons veiller à ce que la complexité du viewmodel ne s'intensifie pas au point de devenir un 'God Object'.
Negative modal 'must ensure that... does not'.
Colocações comuns
Frases Comuns
— The architectural pattern (Model-View-ViewModel) where the viewmodel is a central component.
Our team decided to adopt the MVVM pattern for all new projects.
— The design principle of dividing a program into distinct sections, which the viewmodel helps achieve.
Using a viewmodel promotes separation of concerns between the UI and the data.
— The technique that connects the viewmodel's data to the UI elements automatically.
Two-way data binding allows the viewmodel to update when the user types in a text field.
— The current condition of the user interface, which is managed by the viewmodel.
The viewmodel exposes the UI state as a single object.
— The part of the program that encodes the real-world rules, which should generally stay out of the viewmodel.
The viewmodel should call the repository for business logic instead of handling it itself.
— Logic related to how data is displayed, which is the primary responsibility of the viewmodel.
Formatting a date for the screen is a classic example of presentation logic.
— A component that responds to changes in the lifecycle status of another component, like a viewmodel.
Android viewmodels are lifecycle-aware and survive configuration changes.
— The practice of structuring data models so that every data element is mastered in only one place.
The viewmodel acts as the single source of truth for the screen's state.
— Sections of code that are repeated in many places with little variation, which viewmodels help reduce.
The viewmodel pattern reduces the boilerplate code needed to sync the UI with the data.
— A programming paradigm concerned with data streams and the propagation of change, often used with viewmodels.
We use reactive programming to bind the viewmodel to the UI.
Frequentemente confundido com
The Model is the raw data; the ViewModel is the data formatted for the screen.
A Controller often handles routing and input; a ViewModel handles UI state and binding.
The View is the visual layout; the ViewModel is the logic behind that layout.
Expressões idiomáticas
— Avoid making a single viewmodel responsible for too many different features or screens.
The login and registration should have separate classes; don't put all your eggs in one viewmodel.
Informal/Tech-slang— A user interface that has no logic and only displays what the viewmodel tells it to.
We want a dumb view that just renders whatever the viewmodel provides.
Technical Jargon— An object that knows too much or does too much, often a warning for a bloated viewmodel.
That viewmodel is becoming a God object; we need to break it down.
Technical Jargon— A surface indication that usually corresponds to a deeper problem in the code, like UI references in a viewmodel.
Seeing a 'Context' in a viewmodel is a definite code smell.
Technical Jargon— A viewmodel that contains very little logic, often because the logic has been moved to other layers.
I prefer a skinny viewmodel that just delegates to use cases.
Informal/Tech-slang— The process of connecting the viewmodel to the view and the data sources.
I'm just wiring up the new viewmodel to the repository.
Informal/Tech-slang— When an abstraction (like a viewmodel) fails to completely hide the details it is supposed to.
Exposing database entities directly from the viewmodel is a leaky abstraction.
Technical Jargon— The one place where a piece of data is stored and managed.
The viewmodel is the source of truth for the current UI state.
Technical Jargon— Code that requires a lot of repetitive setup, which some viewmodel implementations are criticized for.
The old way of creating viewmodels was very boilerplate heavy.
Informal/Tech-slang— A confusing mess of different state variables in a viewmodel that are hard to track.
We need to refactor this state soup into a single UI state object.
Informal/Tech-slangFácil de confundir
Both handle UI logic in similar patterns (MVP vs MVVM).
A Presenter usually has a direct reference to the View, while a ViewModel uses data binding and is agnostic of the View.
In MVP, the presenter calls 'view.showError()'; in MVVM, the viewmodel sets 'showError = true'.
Both contain the word 'Model'.
A Data Model represents a database record; a ViewModel represents the state of a specific screen.
The User Data Model has a password field, but the User ViewModel does not.
A viewmodel often contains the state.
State is the data itself; the ViewModel is the object that manages and exposes that state.
The viewmodel holds the UI state.
In Android, they are often used together.
A Fragment is a part of the UI; a ViewModel is the logic component that the Fragment uses.
The Fragment observes the ViewModel.
Both are architectural components.
A Repository handles data fetching (network/DB); a ViewModel handles UI logic and calls the Repository.
The viewmodel asks the repository for the user list.
Padrões de frases
The [noun] is [adjective].
The viewmodel is good.
I use a [noun] for [purpose].
I use a viewmodel for the list.
The [noun] handles the [logic] for [screen].
The viewmodel handles the logic for the login screen.
By using a [noun], we can [benefit].
By using a viewmodel, we can survive screen rotations.
The [noun] encapsulates [logic], ensuring [result].
The viewmodel encapsulates presentation logic, ensuring a clean separation.
Centralizing [process] within the [noun] mitigates [risk].
Centralizing state management within the viewmodel mitigates the risk of UI bugs.
The [noun] serves as an abstraction of [component].
The viewmodel serves as an abstraction of the view.
The [noun] exposes [data] that the [component] observes.
The viewmodel exposes LiveData that the fragment observes.
Família de palavras
Substantivos
Verbos
Adjetivos
Relacionado
Como usar
Extremely high in software development; non-existent in general conversation.
-
Putting UI references in the viewmodel.
→
Expose data that the UI observes.
References to buttons or text views in a viewmodel lead to memory leaks and make testing impossible.
-
Handling network calls directly in the viewmodel.
→
Call a repository that handles the network call.
The viewmodel should coordinate data, not know the details of how to fetch it from the internet.
-
Forgetting to clear observers.
→
Use lifecycle-aware components or clear them in onCleared().
Active observers can keep the viewmodel in memory even after it's no longer needed, wasting resources.
-
Using the viewmodel for global app state.
→
Use a Repository or a specialized State Store.
Viewmodels are scoped to specific screens. Using them for global data makes the app's data flow confusing.
-
Mixing business logic with presentation logic.
→
Move business rules to a separate 'Domain' or 'Model' layer.
Viewmodels should only care about how data is shown, not the core rules of the business.
Dicas
Keep it UI-Agnostic
Ensure your viewmodel doesn't import any UI libraries. It should only deal with data and logic, making it easy to test.
Unit Test Everything
Since viewmodels don't need a UI, write unit tests for every public method and state change to ensure stability.
Use UI State Objects
Instead of many separate variables, expose a single 'ViewState' data class. This makes the UI easier to manage and debug.
Avoid Heavy Logic
Don't do heavy processing on the main thread in a viewmodel. Use background threads or coroutines for network and DB work.
No Contexts
Never pass an Android Context into a viewmodel. If you need a context, use the 'AndroidViewModel' class which provides the Application context safely.
Single Responsibility
If a viewmodel gets too big, split it. Each viewmodel should focus on one specific part of the user's journey.
Expose Immutable Data
Expose data as 'LiveData' or 'StateFlow' so the View can't change it directly. Only the viewmodel should update its own state.
Event Handling
Use a 'SingleLiveEvent' or a Channel for one-time events like navigation or showing a snackbar to avoid repeating them on rotation.
Designer Sync
Use the viewmodel as a contract between you and the UI designer. It defines exactly what data is available for the screen.
Log State Changes
Logging every time the viewmodel state changes can help you quickly find why the UI is showing the wrong thing.
Memorize
Mnemônico
Think of 'VIEW-MODEL' as 'VIEW's MODern hELper'. It helps the View stay modern and clean by handling all the messy logic behind the scenes.
Associação visual
Imagine a theater. The 'View' is the stage and the actors. The 'Model' is the script and the props in the back. The 'ViewModel' is the stage manager who stands in the wings, making sure the right actors go out at the right time with the right props.
Word Web
Desafio
Try to explain what a viewmodel does to someone who doesn't know anything about computers, using only a kitchen metaphor. If you can do it in under 3 sentences, you truly understand the concept.
Origem da palavra
The term 'ViewModel' was coined in 2005 by John Gossman, a software architect at Microsoft. It was introduced as part of the Model-View-ViewModel (MVVM) pattern, which was designed to leverage the data-binding features of the Windows Presentation Foundation (WPF). The name is a portmanteau of 'View' and 'Model,' signifying its role as a model specifically for the view.
Significado original: A model of the view; a non-visual class that represents the state and behavior of a user interface.
English (Technical/Computing)Contexto cultural
No specific sensitivities; it is a neutral technical term.
In English-speaking tech circles, 'ViewModel' is often used as a proper noun in code but a common noun in speech.
Pratique na vida real
Contextos reais
Mobile App Development
- Android ViewModel lifecycle
- SwiftUI @StateObject viewmodel
- Shared viewmodel between fragments
- ViewModel state management
Code Architecture Discussion
- Separation of concerns
- Decoupling the UI
- Presentation logic abstraction
- MVVM implementation
Unit Testing
- Mocking the repository in the viewmodel
- Testing viewmodel state changes
- ViewModel unit test coverage
- Headless testing of UI logic
Job Interviews
- Experience with MVVM
- How do you handle configuration changes?
- Benefits of using a viewmodel
- Managing complex UI state
Technical Documentation
- The ViewModel class
- Binding properties to the viewmodel
- Exposing data via LiveData
- ViewModel constructor parameters
Iniciadores de conversa
"How do you usually structure your viewmodels to avoid them becoming too large?"
"Do you prefer using a single UI state object in your viewmodel or multiple separate streams?"
"What are your thoughts on sharing a viewmodel across multiple screens in a navigation flow?"
"Have you ever encountered a situation where a viewmodel was actually overkill for a simple screen?"
"How do you handle navigation logic—do you put it in the viewmodel or use a separate component?"
Temas para diário
Describe a time when using a viewmodel helped you solve a difficult bug related to screen state.
Write about the pros and cons of the MVVM pattern compared to other architectures you have used.
If you had to explain the concept of a viewmodel to a junior developer, what metaphors would you use?
Reflect on a project where the viewmodels became too 'fat.' How would you refactor them now?
How has the concept of the viewmodel changed your approach to building user interfaces?
Perguntas frequentes
10 perguntasThe main purpose is to separate the UI logic from the UI layout. This makes the code cleaner, easier to maintain, and significantly easier to test because the logic is not tied to a specific screen implementation.
No, it should never hold a reference to a View or a Context. Doing so can cause memory leaks because the viewmodel often lives longer than the View. Instead, the View should observe the viewmodel.
In frameworks like Android, the system keeps the viewmodel in memory while the Activity is destroyed and recreated. When the new Activity starts, it reconnects to the existing viewmodel.
Generally, no. Business logic (like calculating a loan interest rate) should be in the Model or a Domain layer. The viewmodel should only handle presentation logic (like formatting that interest rate as a percentage string).
Usually, yes. However, for very complex screens, you might break it down into multiple viewmodels, or use a shared viewmodel if multiple screens need to access the same data flow.
A Presenter (in MVP) usually has a direct reference to the View through an interface. A ViewModel (in MVVM) does not know about the View and instead exposes data that the View binds to.
If the screen has no logic and the data never changes, a viewmodel might be overkill. However, using one consistently can help maintain a standard architecture across your app.
Most frameworks use a 'Factory' pattern or Dependency Injection (like Hilt or Koin) to provide parameters to a viewmodel when it is created.
Yes, this is common in 'Master-Detail' flows where a list and a detail screen share the same data. This is called a Shared ViewModel.
It is cleared when the scope it is attached to is permanently destroyed, such as when a user closes the app or finishes an activity (not just a rotation).
Teste-se 200 perguntas
Explain the difference between a Model and a ViewModel in your own words.
Well written! Good try! Check the sample answer below.
Describe a scenario where a ViewModel would be essential for a mobile app.
Well written! Good try! Check the sample answer below.
Write a short paragraph explaining why ViewModels are beneficial for unit testing.
Well written! Good try! Check the sample answer below.
List three things that should never be included in a ViewModel.
Well written! Good try! Check the sample answer below.
Explain the concept of 'Separation of Concerns' in the context of MVVM.
Well written! Good try! Check the sample answer below.
How does a ViewModel help manage the state of a complex form?
Well written! Good try! Check the sample answer below.
Describe the lifecycle of a ViewModel in an Android application.
Well written! Good try! Check the sample answer below.
What is a 'Shared ViewModel' and when should you use it?
Well written! Good try! Check the sample answer below.
Compare the ViewModel pattern to the MVC pattern.
Well written! Good try! Check the sample answer below.
Write a sample code description for a ViewModel that handles a login button click.
Well written! Good try! Check the sample answer below.
Why is it important for a ViewModel to be 'UI-agnostic'?
Well written! Good try! Check the sample answer below.
Explain the role of 'onCleared' in resource management.
Well written! Good try! Check the sample answer below.
How would you refactor a 'Fat ViewModel' into smaller components?
Well written! Good try! Check the sample answer below.
Describe the relationship between a ViewModel and a Repository.
Well written! Good try! Check the sample answer below.
What are the disadvantages of using a ViewModel for very simple screens?
Well written! Good try! Check the sample answer below.
Explain how data binding simplifies the interaction between a View and a ViewModel.
Well written! Good try! Check the sample answer below.
What is the 'Single Source of Truth' principle and how does it apply to ViewModels?
Well written! Good try! Check the sample answer below.
How do you handle navigation events from a ViewModel without violating architectural principles?
Well written! Good try! Check the sample answer below.
Describe the historical origin of the ViewModel term.
Well written! Good try! Check the sample answer below.
Write a mnemonic to help a beginner remember what a ViewModel does.
Well written! Good try! Check the sample answer below.
Explain the role of a ViewModel in a stand-up meeting.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Describe how a ViewModel handles a user login attempt.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Discuss the pros and cons of using a Shared ViewModel.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Explain the concept of 'UI State' to a teammate.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
How would you explain a ViewModel to a non-technical client?
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Talk about a time you had to refactor a large ViewModel.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Explain why ViewModels shouldn't have references to Views.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Describe the benefits of MVVM over MVC in a technical interview.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Discuss how ViewModels improve the testability of an app.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Explain the lifecycle of a ViewModel to a junior developer.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
How do you handle error states in your ViewModels?
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Describe the process of data binding between a View and a ViewModel.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
What are your favorite tools for ViewModel dependency injection?
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Explain the 'Single Source of Truth' concept using a ViewModel example.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Discuss the impact of the ViewModel pattern on app performance.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
How do you keep your ViewModels 'skinny'?
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Explain the difference between a ViewModel and a State Holder.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Describe how a ViewModel survives a configuration change.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Talk about the importance of immutability in ViewModel state.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Explain the 'onCleared' method and why it's necessary.
Read this aloud:
Você disse:
Speech recognition is not supported in your browser. Try Chrome or Edge.
Listen to a description of a software bug. Is the bug in the View or the ViewModel?
Listen to a developer's stand-up update. What is their main task regarding the ViewModel?
Listen to a technical talk about MVVM. What are the three components mentioned?
Listen to a code review comment. What is the reviewer's concern about the ViewModel?
Listen to an explanation of data binding. How does the ViewModel update the UI?
Listen to a discussion about unit testing. Why is the ViewModel mentioned?
Listen to a comparison of architectural patterns. What is the main advantage of the ViewModel?
Listen to a tutorial on Android development. How do you instantiate a ViewModel?
Listen to a senior developer explain Clean Architecture. Where does the ViewModel fit in?
Listen to a conversation about memory leaks. How can a ViewModel cause one?
Listen to a podcast about the history of tech. Who invented the ViewModel pattern?
Listen to a bug report. Does the user mention a UI issue or a logic issue in the ViewModel?
Listen to a team lead discussing refactoring. What is their plan for the 'Fat ViewModel'?
Listen to an explanation of SwiftUI. What is the role of the @Published property in a ViewModel?
Listen to a student asking a question about ViewModels. What is their main confusion?
/ 200 correct
Perfect score!
Summary
The viewmodel is the 'brain' of a specific screen; it takes raw data from the back-end, processes it into a user-friendly format, and holds it ready for the UI to display, making the app organized and testable. Example: A viewmodel takes a raw date like '2023-10-27' and turns it into 'October 27th' for the screen.
- A viewmodel is a mediator in software architecture that prepares and manages data specifically for a user interface screen, ensuring a clean separation of concerns.
- It acts as the 'source of truth' for the UI state, handling logic like data formatting, validation, and user interaction processing without direct UI references.
- Commonly used in the MVVM (Model-View-ViewModel) pattern, it helps developers create apps that are more modular, easier to test, and resilient to lifecycle changes.
- By decoupling the UI from the business logic, viewmodels allow designers and developers to work independently and improve the overall maintainability of large codebases.
Keep it UI-Agnostic
Ensure your viewmodel doesn't import any UI libraries. It should only deal with data and logic, making it easy to test.
Unit Test Everything
Since viewmodels don't need a UI, write unit tests for every public method and state change to ensure stability.
Use UI State Objects
Instead of many separate variables, expose a single 'ViewState' data class. This makes the UI easier to manage and debug.
Avoid Heavy Logic
Don't do heavy processing on the main thread in a viewmodel. Use background threads or coroutines for network and DB work.
Exemplo
The ViewModel exposes a list of users to the RecyclerView adapter.
Conteúdo relacionado
Ver em vídeos
Gramática relacionada
Mais palavras de Technology
abautoal
C1Um método ou processo técnico para o alinhamento e integração automáticos de estruturas de dados ou unidades linguísticas díspares, garantindo a sincronização sem intervenção manual.
abautoence
C1Automatizar ou otimizar sistematicamente um processo por meio de mecanismos autônomos ou rotinas autônomas. Descreve o ato de delegar tarefas manuais para sistemas técnicos ou habituais em segundo plano para maximizar a eficiência e reduzir a carga cognitiva.
ablogtion
C1Ablogtionar significa remover sistematicamente registros digitais e entradas de log cronológicas de uma plataforma para gerenciar a reputação online.
abmanless
C1Remover a necessidade de intervenção humana manual de um sistema através da automação total.
activation
B2A ativação é o processo de tornar algo funcional ou operacional, como a ativação de um novo software.
actuator
B2Um atuador é um componente mecânico responsável por mover e controlar um mecanismo ou sistema.
adpaterable
C1Modificar ou configurar um sistema para que ele se torne compatível com um adaptador.
adpaterward
C1Um 'adapterward' é um componente ou ajuste suplementar integrado a um sistema técnico após sua montagem inicial para garantir compatibilidade com padrões mais recentes. Refere-se a uma 'ponte' física ou digital que facilita a sincronização em estágio posterior entre partes legadas e modernas.
aerospace
B2Relativo ao projeto, fabricação e operação de veículos que voam na atmosfera da Terra ou no espaço sideral.
algorithms
B2Um algoritmo é uma sequência finita de instruções bem definidas e não ambíguas para realizar uma tarefa.