Search code examples
androidandroid-architecture-componentsandroid-livedata

When to use MutableLiveData and LiveData


when to use MutableLiveData and LiveData means the area of using the methods :

MutableLiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData;
}

and when to use this,

LiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData
}

Solution

  • LiveData has no public method to modify its data.

    LiveData<User> getUser() {
        if (userMutableLiveData == null) {
            userMutableLiveData = new MutableLiveData<>();
        }
        return userMutableLiveData
    }
    

    You can't update its value like getUser().setValue(userObject) or getUser().postValue(userObject)

    So when you don't want your data to be modified use LiveData If you want to modify your data later use MutableLiveData