Posts

Showing posts with the label Android Livedata

Cannot Resolve ViewModelProvider Construction In A Fragment?

Answer : Firstly you need to use the latest version of lifecycle extension. It should be: implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0" or any updated version. Then you should use requireActivity() instead of getActivity() . This way you will ensure that the activity is attached an not getting a NullPointerException . ItemSetupFragmentModel model = new ViewModelProvider(requireActivity()).get(ItemSetupFragmentModel.class); Note: ViewModel Overview and Declaring Dependencies I had to restart cache after adding the library to the Gradle file. There is no need to use requireActivity() , this is enough. You aren't using the latest library release in which the ViewModelProvider(@NonNull ViewModelStoreOwner owner) constructor was included. You are seeing the latest docs but not using the latest library version of ViewModel . You need to use implementation 'andr...

Android MediatorLiveData Observer

Answer : This answer is largely reproduction of what @CommonsWare has already shared in the comment section above. In order for the callback on MediatorLiveData's addSource method to be triggered, the MediatorLiveData object needs to be observed itself as well. The logic behind this is that the 'mediator' mediates between a LiveData object that it observes, and a final consumer of the data. The mediator is hence an observer and observable simultaneously, and the callback on addSource won't be triggered for the mediator when there are no active observers. As an example; according to Google's Android Architecture Components, an activity or fragment could have an observer observing a mediator on the ViewModel, which in turn may observe other LiveData objects that are handled within the ViewModel or a referenced to an utility class. @CommonsWare pointed out the use of the Transformation class that exposes methods map and switchMap , but these were not ...