Transformations.map() returning null

631 Views Asked by At

I am writing a Kotlin app and using Firestore as my db. I have 2 LiveDatas, 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.

1

There are 1 best solutions below

0
On BEST ANSWER

The reason was that I referred to userData before defining it. My code looked like that:

    private val userDocument = MutableLiveData<DocumentSnapshot?>()

    init {
        Authentication.currentUser.observeForever { switchUserDocument(it?.uid ?: "") }
    }

    val userData = Transformations.map(userDocument) { it?.toObject(UserModel::class.java) }

    private fun switchUserDocument(id: String): Task<DocumentSnapshot>? {
        if (id.isEmpty()) {
            ...
        } else if ((userData.value?.id ?: "") != id) {
            ...
        }
    }

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:)