Search code examples
androidkotlinviewmodel

Posting to LiveData from Coroutine to Update UI even if LiveData Will Only Update Once


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!


Solution

  • 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:

    • Your fragment is created
    • Your viewmodel is created and you kick off the network I/O
    • Your fragment instantiates its UI
    • Your fragment observes the LiveData
    • Your coroutine completes and your viewmodel updates the LiveData
    • Your fragment receives the value from the LiveData and updates the UI
    • The user twists her wrist and rotates the screen
    • Your fragment is destroyed
    • Your replacement fragment is created
    • Your viewmodel is retained, and your replacement fragment gets that same viewmodel with the same LiveData
    • Your replacement fragment instantiates its UI
    • Your replacement fragment observes the LiveData
    • Your replacement fragment receives the value from the LiveData and updates the UI

    So, what you are describing is generally reasonable.