android-viewmodel
Sharing viewModel within Jetpack Compose Navigation
Consider passing your activity to viewModel() fun as viewModelStoreOwner parameter since ComponentActivity implements ViewModelStoreOwner interface: val viewModel: ConversionViewModel = viewModel(LocalContext.current as ComponentActivity) This code will return the same instance of ConversionViewModel in all your destinations.
What is ViewModelStore and viewModelStoreOwner?
Can anyone define them and how to use them and what they really mean to us developer’s? A ViewModelStore can be considered as a container that stores the ViewModels in a HashMap. Where the key is string value and value is the ViewModel being saved(ViewModelProvider uses a concatenation of the string_key + ViewModel class canonical … Read more
Unit test the new Kotlin coroutine StateFlow
It seems that the Android team changed the API and documentation after this thread. You can check it here: Continuous collection SharedFlow/StateFlow is a hot flow, and, as described in the docs, A shared flow is called hot because its active instance exists independently of the presence of collectors. It means the scope that launches … Read more
Android MVVM: Activity with multiple Fragments – Where to put shared LiveData?
Late answer but I asked myself the same question and found the answer in Google guide. Especially for fragments, it is mentioned on Google Documentations explicitly here class SharedViewModel : ViewModel() { val selected = MutableLiveData<Item>() fun select(item: Item) { selected.value = item } } class MasterFragment : Fragment() { private lateinit var itemSelector: Selector … Read more
Scoping States in Jetpack Compose
This is precisely what navigation graph scoped view models are used for. This involves two steps: Finding the NavBackStackEntry associated with the graph you want to scope the ViewModel to Pass that to viewModel(). For part 1), you have two options. If you know the route of the navigation graph (which, in general, you should), … Read more
LiveData prevent receive the last value when start observing
I`m using this EventWraper class from Google Samples inside MutableLiveData /** * Used as a wrapper for data that is exposed via a LiveData that represents an event. */ public class Event<T> { private T mContent; private boolean hasBeenHandled = false; public Event( T content) { if (content == null) { throw new IllegalArgumentException(“null values … Read more
LiveData prevent receive the last value when start observing
I`m using this EventWraper class from Google Samples inside MutableLiveData /** * Used as a wrapper for data that is exposed via a LiveData that represents an event. */ public class Event<T> { private T mContent; private boolean hasBeenHandled = false; public Event( T content) { if (content == null) { throw new IllegalArgumentException(“null values … Read more