当我们有如下的 liveData 时,我们不能_liveData.value++
,因为它是可以value
为空的。
class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
private val _liveData: MutableLiveData<Int> =
savedStateHandle.getLiveData("SomeKey", 0)
val liveData: LiveData<Int> = _liveData
fun triggerLiveData() {
_liveData.value++
}
}
文章https://proandroiddev.com/improving-livedata-nullability-in-kotlin-45751a2bafb7提供了解决方案,即
@Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T>(value: T) : LiveData<T>(value) {
override fun getValue(): T = super.getValue() as T
public override fun setValue(value: T) = super.setValue(value)
public override fun postValue(value: T) = super.postValue(value)
}
但这不支持已保存状态。
我们如何才能获得一个也具有已保存状态的不可为空的 LiveData?