I am writing a Kotlin app and using Firestore as my db. I have 2 LiveData
s, to keep my current user's data, defined like so:
private val userDocument = MutableLiveData<DocumentSnapshot?>()
val userData = Transformations.map(userDocument) { it?.toObject(UserModel::class.java) }
somehow userData
is null, and all references to it (for example: userData.value?.id
) throw:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object androidx.lifecycle.LiveData.getValue()' on a null object reference
If I add ?
(userData?.value?.id
) I get the Unnecessary safe call on a non-null receiver of type LiveData<UserModel?>
lint. How can Transformations.map(...)
return null?
btw: I saw this similar question, but in my case, I do initialize the referedMutableLiveData
.
The reason was that I referred to
userData
before defining it. My code looked like that:I forgot that in Kotlin the order of definition and
init
blocks matters, and lost some time for that. Hope it will save that time to someone in the future:)