0% found this document useful (0 votes)
11 views

Android Interview Masterclass - #1 ViewModel Questions

Uploaded by

Muhammad Nur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Android Interview Masterclass - #1 ViewModel Questions

Uploaded by

Muhammad Nur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Mastering ViewModel For

Android Interview
By - Rahnuma Sharib

Presented By:
Olivia Wilson
WHAT IS VIEW MODEL
ViewModel is a component of the Android Architecture Components that stores and
manages UI-related data in a lifecycle-aware manner. It survives configuration changes.
and facilitates the separation of concerns between UI and data management. The
ViewModel does not directly reference UI components, promoting modularity and
maintainability.

By Rahnuma Sharib
KEY FEATURES OF A VIEWMODEL
Lifecycle Awareness: ViewModels are aware of the lifecycle of the UI components (like an Activity or Fragment)
they are associated with. They are automatically destroyed when the associated UI component is destroyed.

Surviving Configuration Changes: ViewModels persist data across configuration changes, such as screen
rotations, by surviving the destruction and recreation of the UI components.

Separation of Concerns: ViewModels help in separating the concerns of data management from the UI
components. This separation enhances the readability, testability, and maintainability of the code.

Communication between Fragments and Activities: ViewModels can be shared between fragments and their
associated activity or between different fragments within the same activity. This makes it easier to share data
and communicate between various parts of the UI.

By Rahnuma Sharib
BENEFITS OF A VIEWMODEL
Surviving Configuration Changes:
ViewModels are lifecycle-aware, allowing them to survive configuration changes like screen rotations. This
ensures that UI-related data persists across these changes, reducing the need to reload or recreate data.

Data Sharing Between Components:


ViewModels facilitate communication and data sharing between different UI components, such as an
Activity and its associated Fragments. This is done without the components having direct references to each
other, leading to a more loosely coupled architecture.

Lifecycle Awareness:
ViewModels are tied to the lifecycle of the associated UI component. This ensures that resources are released
appropriately when the UI component is destroyed, preventing memory leaks and improving overall
resource management.

Separation of Concerns:
ViewModels separate the UI-related logic from the UI components (such as Activities or Fragments). This
separation makes the codebase more modular, readable, and easier to maintain.

By Rahnuma Sharib
MOST ASKED ANDROID INTERVIEW QUESTION ON
VIEW MODEL
What is a ViewModel in Android, and why is it used?
Benefit of using view model / key characteristics of view model
How to create instance of viewmodel.
Can ViewModels be used to share data between multiple Fragments in the same Activity?
Difference between shared view model and view model.
What is the difference between ViewModel and AndroidViewModel.
Explain the role of the ViewModelProvider in Android.
What is view-model factory & how to pass data in view model constructor

Most Importent Question for senior or Intermediate level.


How ViewModel work internally.
How ViewModel retain data during configuration change.
During configuration change activity distroy and re-create then how view-model instance remain same.
Explain the difference between ViewModel and onSaveInstanceState.

By Rahnuma Sharib
How to create instance of viewmodel.

ViewModel() constructor:
Conciseness: It reduces boilerplate code, making it concise and readable.
It may offer limited control over the ViewModel creation process, which could be a disadvantage in
scenarios where you need more customization.

By Rahnuma Sharib
How to create instance of viewmodel.

With ViewModelProvider :
Lifecycle-aware, supports shared ViewModels, and allows custom initialization.
Involves some boilerplate code, no built-in support for automatic dependency injection, and may
look different in Java.

By Rahnuma Sharib
How to create instance of viewmodel.

ViewModelFactory :
we can pass parameter into the
constructer of view model.
Dependency Injection: You can
inject dependencies into your
ViewModel, making it more
testable and modular.
Separation of Concerns: Keeps the
creation logic separate from the
actual ViewModel, promoting a
cleaner architecture.

By Rahnuma Sharib
Can ViewModels be used to share data between multiple
Fragments in the same Activity?

yes : Yes, ViewModels in Android are often used to share data between multiple
fragments within the same activity..

By Rahnuma Sharib
How to create instance of viewmodel.
The primary difference between initializing a shared ViewModel and a regular ViewModel in Kotlin lies
in how you obtain the instance of the ViewModel.

ViewModel:
When initializing a regular ViewModel, you typically
use ViewModelProvider within the scope of an
individual fragment or activity.

Shared ViewModel:
Shared ViewModel (sharedViewModel) is
initialized using activityViewModels() to share the
same instance among multiple fragments within
the same activity.

In this example, activityViewModels() is an extension property provided by the activity-ktx library, and it's part of the
AndroidX Navigation component. This property is used to create or retrieve a ViewModel scoped to the activity.

By Rahnuma Sharib
What is the difference between ViewModel and AndroidViewModel.
ViewModel and AndroidViewModel are classes provided by the Android Architecture Components
While they share some common features, there are key differences between them:
Context
Constructor
ViewModel Does not have direct access to the application
View model Has a default constructor and doesn't take any parameters.
context or any Android-related resources.and Primarily used for AndroidViewModel Requires an application context parameter in its
holding and managing UI-related data. constructor.
AndroidViewModel : extends ViewModel and includes the
application context as a parameter in its constructor. Initialization
Allows direct access to the application context and can be used ViewModel: Typically initialized using ViewModelProvider without any

to access resources like SharedPreferences or Resources. additional context.


AndroidViewModel: Initialized using ViewModelProvider with the
application context.

5. Use Cases:
Use Case:
ViewModel: Used in scenarios where UI-related data needs to be
ViewModel: Used in scenarios where UI-related data needs to be retained
retained during configuration changes (e.g., screen rotations) and during configuration changes (e.g., screen rotations) and the logic doesn't
the logic doesn't involve Android-specific functionality. involve Android-specific functionality..
AndroidViewModel : Appropriate when the ViewModel needs AndroidViewModel: Appropriate when the ViewModel needs access to
access to the application context or resources, such as handling the application context or resources, such as handling preferences or
preferences or accessing system services. accessing system services..

By Rahnuma Sharib
Explain the role of the ViewModelProvider in Android.

Purpose: ViewModelProvider is a utility class in Android used to create and obtain instances of ViewModel in a lifecycle-
aware manner.
ViewModel Creation: It facilitates the creation of ViewModels associated with the lifecycle of an activity or fragment,
ensuring that the same ViewModel instance survives configuration changes.
Scope Management: Manages the scoping of ViewModels, preventing unnecessary creation of new instances and
facilitating the sharing of ViewModels between related components.
Constructor Parameter: Typically takes an instance of an activity or fragment as a parameter, tying the ViewModel's
lifecycle to that of the associated UI component.
Custom Factories: Allows the use of custom factories for ViewModel creation, enabling dependency injection and
customization.
Prevents Memory Leaks: Helps prevent memory leaks by properly managing the lifecycle of ViewModels, ensuring they are
cleared when no longer needed.

By Rahnuma Sharib
What is view-model factory & how to pass data in view model constructor
Purpose: The ViewModel factory is responsible for creating instances of ViewModels, especially when those ViewModels
have non-empty constructors requiring additional parameters.
Customization : Allows you to customize the process of ViewModel creation, making it possible to inject dependencies or
pass data to the ViewModel's constructor.

class MyViewModelFactory(private val initialData:


String) : ViewModelProvider.Factory

By Rahnuma Sharib
How ViewModel work internally.
How ViewModel retain data during configuration change.
During configuration change activity distroy and re-create then how view-model instance remain same.

ViewModelStore::
Each activity and fragment has its own ViewModelStore, which is responsible for managing ViewModel instances
associated with that scope.
When a new instance of an activity or fragment is created (e.g., due to a configuration change), it has access to the same
ViewModelStore as the previous instance.
The ViewModelStore retains references to the existing ViewModel instances.

Step 1:

By Rahnuma Sharib
How ViewModel work internally.
How ViewModel retain data during configuration change.
During configuration change activity distroy and re-create then how view-model instance remain same.

ViewModelStoreOwner is a simple interface with a single method named getViewModelStore()

By Rahnuma Sharib
How ViewModel work internally.
How ViewModel retain data during configuration change.
During configuration change activity distroy and re-create then how view-model instance remain same.

By Rahnuma Sharib
How ViewModel work internally.
How ViewModel retain data during configuration change.
During configuration change activity distroy and re-create then how view-model instance remain same.

How ViewModel retain itself?


As we saw earlier when we created
ViewModelProvider we were passing an
instance of ViewModelStoreOwner i.e., our
activity instance.

Now let’s have a look at the implementation


of this interface ViewModelStoreOwner

By Rahnuma Sharib
How ViewModel work internally.
How ViewModel retain data during configuration change.
During configuration change activity distroy and re-create then how view-model instance remain same.

How ViewModel retain itself?


As we saw earlier when we created
ViewModelProvider we were passing an
instance of ViewModelStoreOwner i.e., our
activity instance.

Now let’s have a look at the implementation


of this interface ViewModelStoreOwner

By Rahnuma Sharib
Explain the difference between ViewModel and
onSaveInstanceState.

ViewModel:
ViewModel is used for managing and persisting UI-related data across configuration
changes and is associated with the lifecycle of the UI component.

onSaveInstanceState
is used for saving simple UI state data temporarily during configuration changes
and is part of the Android activity and fragment lifecycle.

In some cases, you might use both mechanisms to ensure comprehensive handling of state within
your Android application. ViewModel is often preferred for more complex and larger datasets, while
onSaveInstanceState is suitable for smaller UI state data.

By Rahnuma Sharib

You might also like