How to get preview in composable functions that depend on a view model?

This is exactly one of the reasons why the view model is passed with a default value. In the preview, you can pass a test object: @Preview @Composable private fun HomeScreenPreview() { val viewModel = HomeViewModel() // setup viewModel as you need it to be in the preview HomeScreen(viewModel = viewModel, navigateToDetailsAction = {}, openCardDetailsAction … Read more

ViewModelProviders is deprecated in 1.1.0

I use lifecycle-extensions 2.2.0 version: implementation “androidx.lifecycle:lifecycle-extensions:2.2.0” It should work, using ViewModelProvider constructor. // With ViewModelFactory val viewModel = ViewModelProvider(this, YourViewModelFactory).get(YourViewModel::class.java) //Without ViewModelFactory val viewModel = ViewModelProvider(this).get(YourViewModel::class.java) 2020/5/15 Update I found another elegant way to achieve this, Android KTX can help implementation “androidx.fragment:fragment-ktx:1.2.4” val viewmodel: MYViewModel by viewModels() val viewmodel: MYViewModel by viewModels { myFactory … 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

AndroidViewModel vs ViewModel

AndroidViewModel provides Application context If you need to use context inside your Viewmodel you should use AndroidViewModel (AVM), because it contains the application context. To retrieve the context call getApplication(), otherwise use the regular ViewModel (VM). AndroidViewModel has application context. We all know having static context instance is evil as it can cause memory leaks!! … Read more