Nullability and LiveData with Kotlin

前端 未结 8 1593
梦谈多话
梦谈多话 2021-02-19 02:57

I want to use LiveData with Kotlin and have values that should not be null. How do you deal with this? Perhaps a wrapper around LiveData? Searching for good patterns here .. As

8条回答
  •  悲哀的现实
    2021-02-19 03:04

    I really liked The Lucky Coder's answer. Regarding the danger on trying to set a null value, I think we should throw an exception for this (similar to what David Whitman was pointing):

    class NonNullLiveData(private val defaultValue: T) : MutableLiveData() {
    
    override fun getValue(): T = super.getValue() ?: defaultValue
    
    override fun setValue(value: T) {
        if(value != null) {
            super.setValue(value)
        }
        else throw IllegalArgumentException("Cannot set a null value to this Type. Use normal MutableLiveData instead for that.")
    }
    
    override fun postValue(value: T) {
        if(value != null) {
            super.postValue(value)
        }
        else throw IllegalArgumentException("Cannot post a null value to this Type. Use normal MutableLiveData instead for that.")
    }
    
    fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
        observe(owner, Observer {
            body(it ?: defaultValue)
        })
    }
    

    }

    Now the value in the MutableLiveData will never be null, so that the class would not be used in a way it's not intended.

提交回复
热议问题