何时使用MutableLiveData和LiveData

vin*_*yak 8 android android-livedata android-architecture-components

何时使用MutableLiveData以及LiveData使用方法的范围:

MutableLiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData;
}
Run Code Online (Sandbox Code Playgroud)

以及何时使用

LiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData
}
Run Code Online (Sandbox Code Playgroud)

小智 16

LiveData没有公开可用的方法来更新存储的数据。该类MutableLiveData公开了publicsetValue(T)postValue(T)方法,如果需要编辑存储在LiveData对象中的值,则必须使用这些方法。通常MutableLiveData用在 中ViewModel,然后只向观察者ViewModel公开不可变的对象。LiveData请看一下这个参考


Jee*_*ede 13

比方说,你在下面MVVM架构,并且具有LiveData作为观察的方式从ViewModel你的Activity。这样你就可以让你的变量作为LiveData对象暴露Activity如下:

class MyViewModel : ViewModel() {
    // LiveData object as following
    var someLiveData: LiveData<Any> = MutableLiveData()

    fun changeItsValue(someValue: Any) {
        (someLiveData as? MutableLiveData)?.value = someValue
    }
}
Run Code Online (Sandbox Code Playgroud)

现在Activity部分,您可以观察LiveData但要进行修改,您可以从ViewModel下面调用方法:

class SomeActivity : AppCompatActivity() {
    // Inside onCreateMethod of activity
    val viewModel = ViewModelProviders.of(this)[MyViewModel::class.java]
    viewModel.someLiveData.observe(this, Observer{
        // Here we observe livedata
    })
    viewModel.changeItsValue(someValue) // We call it to change value to LiveData
    // End of onCreate
}
Run Code Online (Sandbox Code Playgroud)

  • @c0ming 另一种方法是通过在 ViewModel 中创建两个对象来实现此目的。`MutableLiveData` 对象可以是私有的并通过 setter 方法操作,而公共对象可以是从上面的私有对象重新分配的 `LiveData` 。 (3认同)

Der*_*k K 9

我们应该返回 LiveData 以防止视图(或其他观察者)意外修改值。

拥有:

    LiveData<User> getUser() {
       if (userMutableLiveData == null) {
           userMutableLiveData = new MutableLiveData<>();
       }
       return userMutableLiveData
    }
Run Code Online (Sandbox Code Playgroud)

你不能在你的活动/片段中写:getUser().setValue(...)。这使您的代码不易出错。


shb*_*shb 5

LiveData没有公共方法来修改其数据。

LiveData<User> getUser() {
    if (userMutableLiveData == null) {
        userMutableLiveData = new MutableLiveData<>();
    }
    return userMutableLiveData
}
Run Code Online (Sandbox Code Playgroud)

您无法像getUser().setValue(userObject)或那样更新其值getUser().postValue(userObject)

因此,当您不希望修改数据时,LiveData 如果以后要修改数据,请使用MutableLiveData

  • 你所说的我们不能错误地更新实时数据值。LiveDate 不是同步的,而是同步的可变实时数据,并且还能够使用其 postValue 方法从工作线程调用观察者。因此,当您不希望修改数据时,请使用 LiveData 如果您想稍后修改数据,请使用 MutableLiveData` 这个不正确的说法。/sf/ask/3276991091/ (4认同)
  • MVVM 新手。我了解到“LiveData”是“ViewModel”与“View”通信的[唯一方式](https://android.jlelse.eu/mvvm-how-view-and-viewmodel-should-communicate-8a386ce1bb42)。那么不可变的“LiveData”有什么意义呢? (2认同)