salyela
salyela

Reputation: 1645

LiveData is passing null to observer

I have the following code

myViewModel.catLiveData.observe(this,Observer{
  if(it==null){
      Log.d(TAG,"the object returned is null! How is that possible?")
  }else{ doWork(it) }
})

How is it possible that I am getting null? I thought LiveData is not supposed to pass null to the observer? This LiveData is listening to Room Entity, by the way.

Upvotes: 0

Views: 4248

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134664

LiveData definitely allows null to be sent through to the observers if it's specifically posted. You can see that the method signature for android.arch.lifecycle.Observer.onChanged explicitly marks the data parameter as @Nullable.

If you don't wish to handle a null type, you can simply use the ? operator to safely handle it:

myViewModel.catLiveData.observe(this, Observer { it?.let(::doWork) })

Alternatively, you could create your own custom Observer that handles it for you, e.g.

class Observer2<T>(private val block: (T) -> Unit) : Observer<T> {
    override fun onChanged(data: T?) {
        data?.let(block)
    }
}

Which would allow you to write:

myViewModel.catLiveData.observe(this, Observer2(::doWork))

Upvotes: 3

Related Questions