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: LiveData<Int> = _liveData
fun triggerLiveData() {
_liveData.value++
}
}
The article https://proandroiddev.com/improving-livedata-nullability-in-kotlin-45751a2bafb7 provide a solution, i.e.
@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
The usage is as below