The error from the title is returned for the following code, which makes no sense
private val _error = MutableLiveData<String?>()
val error: LiveData<String?> get() = _error
_error.postValue(null) //Error Cannot set non-nullable LiveData value to null [NullSafeMutableLiveData]
parameter String
of _error
is obviously nullable, am I doing something wrong?
LiveData is written in Java. It does allow setting it's value to null .
MutableLiveData. MutableLiveData is just a class that extends the LiveData type class. MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide.
LiveData is a wrapper that can be used with any data, including objects that implement Collections , such as List . A LiveData object is usually stored within a ViewModel object and is accessed via a getter method, as demonstrated in the following example: Kotlin Java. class NameViewModel : ViewModel() {
This appears to be related to a bug already reported against androidx.lifecycle
pre-release of 2.3.0 https://issuetracker.google.com/issues/169249668.
Workarounds I have found:
NullSafeMutableLiveData
inbuild.gradle
android {
...
lintOptions {
disable 'NullSafeMutableLiveData'
}
}
or lint.xml
in root dir
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="NullSafeMutableLiveData" severity="warning" />
</lint>
MutableLiveData
encapsulation via backing properties dance (which really hurts my eyes).class ExampleViewModel : ViewModel() {
private val _data1 = MutableLiveData<Int>()
val data1: LiveData<Int> = _data1
private val _data2 = MutableLiveData<Int?>()
val data2: LiveData<Int?> = _data2
fun funct() {
_data1.value = 1
_data2.value = null
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With