When to use MutableLiveData and LiveData

vinayak picture vinayak · Apr 30, 2019 · Viewed 18.3k times · Source

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
}

Answer

shb picture shb · Apr 30, 2019

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