Questions tagged [android-viewmodel]
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations. For topics related to Android, use Android-specific tags such as android-intent, android-activity, android-adapter, etc. For questions other than development or programming, but related to the Android framework, use this link: https://android.stackexchange.com.
android-viewmodel
1,821
questions
257
votes
4
answers
93k
views
AndroidViewModel vs ViewModel
With the introduction of the Android Architecture Components library, several new classes were introduced, including AndroidViewModel and ViewModel. However, I'm having trouble figuring out the ...
246
votes
30
answers
140k
views
ViewModelProviders is deprecated in 1.1.0
Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:
val model = ViewModelProviders.of(this).get(MyViewModel::class.java)
When using the latest ...
151
votes
14
answers
133k
views
how to get viewModel by viewModels? (fragment-ktx)
I am working with Single viewModel for the Activity and all of its fragment.
So to initialise viewmodel if have to write this setup code in onActivityCreated of all the fragment's
override fun ...
132
votes
10
answers
138k
views
Observing LiveData from ViewModel
I have a separate class in which I handle data fetching (specifically Firebase) and I usually return LiveData objects from it and update them asynchronously. Now I want to have the returned data ...
105
votes
13
answers
77k
views
Manually clearing an Android ViewModel?
Edit: This question is a bit out of date now that Google has given us the ability to scope ViewModel to navigation graphs. The better approach (rather than trying to clear activity-scoped models) ...
100
votes
6
answers
79k
views
When is the viewmodel onCleared called
Are ViewModels independent of activity/fragment lifecycles or just their configuration changes. When will they cease to exist and the subsequent onCleared() method called.
Can the viewModel be shared ...
81
votes
7
answers
90k
views
LiveData update on object field change
I'm using Android MVVM architecture with LiveData. I have an object like this
public class User {
private String firstName;
private String lastName;
public String getFirstName() {
...
79
votes
4
answers
63k
views
Use viewLifecycleOwner as the LifecycleOwner
I have a fragment:
class MyFragment : BaseFragment() {
// my StudentsViewModel instance
lateinit var viewModel: StudentsViewModel
override fun onCreateView(...){
...
}
...
78
votes
4
answers
29k
views
DefaultActivityViewModelFactory not found
After migrating the Hilt version from 2.33-beta to 2.35 my project has stopped building with the error given below:
A txt version:
error: cannot access DefaultActivityViewModelFactory
class ...
58
votes
18
answers
72k
views
LiveData prevent receive the last value when start observing
Is it possible to prevent LiveData receive the last value when start observing?
I am considering to use LiveData as events.
For example events like show message, a navigation event or a dialog ...
55
votes
6
answers
21k
views
Dagger Hilt 'Assisted' and 'ViewModelInject' is deprecated. in Dagger Hilt View Model 1.0.0-alpha03
In Dagger Hilt View Model 1.0.0-alpha01
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01"
implementation 'com.google.dagger:hilt-android:2.28-alpha'
kapt '...
54
votes
4
answers
33k
views
Should I include LifecycleOwner in ViewModel?
LifecycleOwner is currently needed in order for me to create an observer.
I have code which creates an Observer in the ViewModel so I attach the LifecycleOwner when retrieving the ViewModel in my ...
51
votes
5
answers
27k
views
MediatorLiveData or switchMap transformation with multiple parameters
I am using Transformations.switchMap in my ViewModel so my LiveData collection, observed in my fragment, reacts on changes of code parameter.
This works perfectly :
public class MyViewModel extends ...
50
votes
7
answers
33k
views
Sharing viewModel within Jetpack Compose Navigation
Can anyone suggest how to share a ViewModel within different sections of a Jetpack Compose Navigation?
According to the documentation, viewModels should normally be shared within different compose ...
49
votes
2
answers
14k
views
Scoping States in Jetpack Compose
In all applications there will always be this three scopes of state:
With Compose, a "Per Screen State" could be achieved by:
NavHost(navController, startDestination = startRoute) {
...
...
40
votes
9
answers
22k
views
Jetpack Compose pass parameter to viewModel
How can we pass parameter to viewModel in Jetpack Compose?
This is my composable
@Composable
fun UsersList() {
val myViewModel: MyViewModel = viewModel("db2name") // pass param ...
40
votes
1
answer
23k
views
What is ViewModelStore and viewModelStoreOwner?
I am very confused due to this new ViewModelProvider api(ViewModelProviders is deprecated)
As with the new changes there are new Constructors also (Source code).
#1
public ViewModelProvider(@...
40
votes
2
answers
12k
views
Android MVVM: Activity with multiple Fragments - Where to put shared LiveData?
I have an architectural question about the android ViewModels:
Let's say that in my App I have an Activity with two Fragments inside (using a Viewpager). The two fragments do different things (...
38
votes
8
answers
30k
views
Unit test the new Kotlin coroutine StateFlow
Recently, the class StateFlow was introduced as part of Kotlin coroutines.
I'm currently trying it and encountered an issue while trying to unit test my ViewModel. What I want to achieve: testing that ...
33
votes
2
answers
6k
views
Retrofit call in Kotlin Coroutines viewModelScope
Recently I've updated my ViewModel to use new viewModelScope. From its implementation, I see that Dispatchers.Main.immediate is set as the default CoroutineDispatcher for viewModelScope.
So when ...
32
votes
4
answers
13k
views
Scoping a viewmodel to multiple fragments (not activity) using the navigation component
I'm using the navigation component, I want a view model to be shared between a few fragments but they should be cleared when I leave the fragments (hence not scoping them to the activity) I'm trying ...
31
votes
4
answers
26k
views
How to pass runtime parameters to a ViewModel's constructor when using Hilt for dependency injection?
I'm wondering how to pass runtime parameters to a ViewModel's constructor while using Hilt for DI? Prior to using Hilt, I have a ViewModel that looks like this:
class ItemViewModel(private val itemId: ...
31
votes
1
answer
16k
views
Is it correct to bind a ViewModel to a Service?
I've started using Architecture Components in my application and I'm still learning how to use it.
In my app I have an Activity showing different Fragments sequentially. In some of them I need to ...
27
votes
5
answers
27k
views
Android ViewModel and startActivity
I am learning ViewModel and LiveData and, in the process, a doubt arose.
What should I do if I need to start an Activity?
Is it ok to pass the context as a parameter to the ViewModel (the context ...
26
votes
2
answers
22k
views
How to use a ViewModelProvider.Factory when extends from AndroidViewModel
I want to send an extra parameter to my ViewModel, but this extends from AndroidViewModel.
How can I add this parameter to the ViewModelFactory class ?
ViewModel
class ProjectViewModel(application: ...
26
votes
2
answers
16k
views
Setting up LiveData observer in custom view without LifecycleOwner
I'm trying out the new Android Architecture components and have run into a road block when trying to use the MVVM model for a custom view.
Essentially I have created a custom view to encapsulate a ...
25
votes
3
answers
13k
views
Navigation with MVVM android
I have an app using Androids ViewModel class and Navigation Component for navigating between fragments. How would I handle navigation from the ViewModel? I am using RxJava and I was thinking of having ...
24
votes
4
answers
38k
views
View models for RecyclerView items
My activity has a Google's ViewModel that fetches some model items. These items are then transformed into adapter items of a RecyclerView. There are also many types of adapter items supported by one ...
24
votes
1
answer
6k
views
How to mock the view model with Hilt for unit testing fragments?
I've got an android app setup for dependency injection using Hilt, and would like to unit test my fragments.
I'm currently creating my view model using:
private val viewModel: ExampleViewModel by ...
24
votes
3
answers
10k
views
Sharing Data between ViewModels
I have a complex screen in my project which I'm breaking in more than one fragment. I'm trying to follow the MVVM architecture for these classes, so which fragment has its own ViewModel and Contract ...
23
votes
3
answers
12k
views
How to use Hilt to inject a safe-args argument into a viewmodel?
I have found a similar question here. At the time of writing this question there is only this answer avaliable, which does not provide any help to me, and I believe also to the person who asked the ...
23
votes
7
answers
69k
views
Failed to resolve: androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1
I am trying to understand ViewModel and LiveData concepts in android. I am making a practice project but when i added implementation 'androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1' line in ...
21
votes
8
answers
29k
views
Dagger-Hilt: @ViewModelInject is not injecting MyViewModel and crash?
In exploring the ViewModelInject of Dagger-Hilt, I follow the example in https://developer.android.com/training/dependency-injection/hilt-jetpack#viewmodels
I try to inject the ViewModel into my ...
21
votes
1
answer
10k
views
How does Android Paging Library know to load more data?
Iʼm fairly new to developing Android apps and Iʼm trying to do everything “the right way.” So right now, Iʼm implementing the new Android Paging Library into my project, where I need to load a list of ...
21
votes
2
answers
13k
views
Does ViewModel survive Activity save and restore?
Instances of the new ViewModel class can survive configuration changes if used in the following fashion:
mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
However, in addition to ...
20
votes
2
answers
11k
views
How ViewModel survives configuration change
I am trying to use ViewModel in my app. The question comes to my mind is How View Model survives configuration changes. I read number of blog posts saying that "
It will create a HolderFragment to ...
20
votes
3
answers
23k
views
Difference between ActivityViewModels and lazy ViewModelProvider?
Difference between ActivityViewModels and lazy ViewModelProvider?
I've seen 2 ways to initialize a viewmodel:
private val someViewModel: SomeViewModel by activityViewModels()
private val ...
20
votes
1
answer
6k
views
Android share ViewModel between fragment and dialog fragment?
How to share same viewModel between dialog and dialogFragment? I know that viewModel can be shared in activity scope. But it is too big scope for me.
private val model: SharedViewModel by ...
20
votes
3
answers
25k
views
Updating UI using ViewModel and DataBinding
I am trying to learn ViewModel in android, in my first phase of learning I am trying to update UI (TextView) by using ViewModel and DataBinding. In ViewModel, I have an AsyncTask callback and it will ...
20
votes
2
answers
14k
views
Android ViewModel inside Service (Alternative)
I have a service which provides UI that is visible to user most of the time.
I was experimenting with new Application Architecture when I came with a problem.
MyModelviewModel viewModel = ...
20
votes
3
answers
23k
views
How do I use the new Saved State Module of ViewModel
I'm using lifecycle version 2.2.0-rc03 and the official docs and articles found don't even list the correct class name or constructor arguments. I think I have to get the ViewModel instance through ...
19
votes
5
answers
14k
views
How to give same instance of ViewModel to both the Parent and Child fragment
There are two Fragments: ParentFragment and ChildFragment.
ChildFragment has been added to a view of the ParentFragment.
Now using Dagger2 for Android has the ParentFragmentModule with a method:
@...
19
votes
2
answers
6k
views
Android Arch Components ViewModel and LiveData trigger after screen rotation
I have a problem when using ViewModel and LiveData arch components. When using fragments and rotating the screen, the observer gets triggered...
I tried to move viewModel = ViewModelProviders.of(this)....
18
votes
4
answers
7k
views
How to ensure ViewModel#onCleared is called in an Android unit test?
This is my MWE test class, which depends on AndroidX, JUnit 4 and MockK 1.9:
class ViewModelOnClearedTest {
@Test
fun `MyViewModel#onCleared calls Object#function`() = mockkObject(Object) {
...
18
votes
4
answers
11k
views
LiveData Transformations.map() with multiple arguments
I have a value in the UI that it's value depends on two LiveData objects. Imagine a shop where you need a subtotal = sum of all items price and a total = subtotal + shipment price. Using ...
18
votes
5
answers
25k
views
How to implement validation using ViewModel and Databinding?
What is the best approach to validate form data using ViewModel and Databinding?
I have a simple Sign-Up activity that links binding layout and ViewModel
class StartActivity : AppCompatActivity() {
...
18
votes
1
answer
2k
views
Understanding Android Architecture Components example GithubBrowserSample: ViewModelModule, ViewModel parameters
One of the most up to date samples covering Android Architecture Components is GithubBrowserSample provided by Google. I reviewed the code and a few questions arose:
I have noticed that ...
17
votes
2
answers
15k
views
ViewPager with viewmodel and live data , all 6 tabs data is replaced by last tab data
I am working on a ViewPager with 6 tabs where it has only one fragment TimesListFragment
Depending on the arguments passed to TimesListFragment it calls api eg; science , technology, travel etc
I ...
17
votes
2
answers
7k
views
When to dispose RxJava2 Disposable in ViewModel?
I'm using ViewModel from Android Architecture Components in my app. In the ViewModel, I'm using RxJava2 subscription and I keep Disposable object after I subscribe. Before, when I did this in Activity,...
17
votes
1
answer
10k
views
When to use withContext?
Currently my code looks like this:
I have a ViewModel that calls the repository to do some background computations and return a result.
The ViewModel function is run with viewModelScope.launch(...