In my ViewModel's constructor, I immediately launch a coroutine to make a one time network call. To update the UI based on the result of this network call, I post updates to a few LiveData variables in my ViewModel. These LiveData variables are, in turn, observed by a fragment which then make the necessary UI updates.
What I'm wondering is if this is a valid way to make UI updates from a coroutine. As I mentioned earlier, the network request is only a one time thing done upon initialization, and so the LiveData variables will never be updated more than once. Is it then wasteful to set up observers in my fragment since I know for a fact they will only be called once? If so, what would be a better way to do this?
Thanks!
Is it then wasteful to set up observers in my fragment since I know for a fact they will only be called once?
They may be called more than once.
Primarily, LiveData
is a value holder. And, specifically, by having LiveData
in a ViewModel
, you retain the LiveData
and the held values across configuration changes (screen rotations, dark mode switch, etc.).
So, the flow may wind up being:
LiveData
LiveData
LiveData
and updates the UILiveData
LiveData
LiveData
and updates the UISo, what you are describing is generally reasonable.