Now surpirisingly in our application, we were already using LiveData.
For example, if you go to the MainViewModel, you’ll find this recipeState LiveData whose value is being updated over here. And in MainActivity within onCreate function we are observing for any value update over here. And I am sure you are able to connect the dots now.
Similarly, if you to FoodTriviaViewModel then you’ll find another LiveData over here whose value is getting update here but this time for this LiveData we have the oberver as FoodTriviaFragment class.
And I guess we are missing something here. We are not yet observing that LiveData inside this Fragment. And I am sure due to this if you go to ‘Food Trivia’, and click this button then nothing happens. Because although on click of button we are making API call to the server via our ViewModel, we haven’t used the LiveData to update the UI in this fragment. Right?
So inside our Fragment incise the onViewCreated method let’s use viewModel, access foodTriviaState LiveData and call observe method. As a parameter pass viewLifecycleOwner, and use Observer lambda.
viewModel.foodTriviaState.observe(viewLifecycleOwner, Observer { foodTriviaApiState ->
handleFoodTriviaApiState(foodTriviaApiState)
})
and call this handleFoodTriviaApiState() function and pass FoodTriviaApiState as paramater by using the it keyword.
Now this function is actually defined over here at the bottom which will update the UI with the new data. If the response is successfull,it will update the TextView i.e. update UI. And if something went wrong, then it will show the error message.
So let’s try it out again.
Go to ‘Food Trivia’. So here we are by default making an API call when the fragment loads. Let’s click on this button again. It updates the data. Again. It again updates the data. Great, isn’t it?
So here as well we are successfully using LiveData and notifying the fragment for its value update.
So yes, that’s all for this episode.