Nullability and LiveData with Kotlin

前端 未结 8 1566
梦谈多话
梦谈多话 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:22

    I little improve answer The Lucky Coder. This implementation cannot accept null values at all.

    class NonNullMutableLiveData(initValue: T): MutableLiveData() {
    
        init {
            value = initValue
        }
    
        override fun getValue(): T {
            return super.getValue()!!
        }
    
        override fun setValue(value: T) {
            super.setValue(value)
        }
    
        fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
            observe(owner, Observer { t -> body(t!!) })
        }
    
        override fun postValue(value: T) {
            super.postValue(value)
        }    
    }
    

提交回复
热议问题