When we have a liveData as below, we cannot _liveData.value++
, as the value
is nullable.
class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
private val _liveData: MutableLiveData<Int> =
savedStateHandle.getLiveData("SomeKey", 0)
val liveData: MutableLiveData<Int> = _liveData
fun triggerLiveData() {
_liveData.value++
}
}
The article https://proandroiddev.com/improving-livedata-nullability-in-kotlin-45751a2bafb7 provide a solution, ie
@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)
}
But that didn't support savedState.
How can we get a non-nullable LiveData that also has savedstate?
I have a solution that duplicate the data and don't look that elegant
@Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T: Any>(private val mutableLiveData: MutableLiveData<T>) :
MutableLiveData<T>(mutableLiveData.value) {
override fun getValue(): T = mutableLiveData.value as T
override fun setValue(value: T) {
super.setValue(value)
mutableLiveData.value = value
}
override fun postValue(value: T) {
super.postValue(value)
mutableLiveData.postValue(value)
}
}
The usage is as below
class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
private val _liveData: SafeMutableLiveData<Int> =
SafeMutableLiveData(savedStateHandle.getLiveData("Something", 0))
val liveData: SafeMutableLiveData<Int> = _liveData
fun triggerLiveData() {
_liveData.value++
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.