Nullability and LiveData with Kotlin

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

    This is my solution.

    class NotNullLiveData
    constructor(private val default: T) : MediatorLiveData() {
        override fun getValue(): T {
            return super.getValue() ?: default
        }
    
        override fun setValue(value: T) {
            super.setValue(value)
        }
    }
    
    @MainThread
    fun  mutableLiveDataOfNotNull(initValue: T): NotNullLiveData {
        val liveData = NotNullLiveData(initValue)
        liveData.value = initValue
        return liveData
    }
    
    @MainThread
    fun  mutableLiveDataOf(initValue: T): MutableLiveData {
        val liveData = MutableLiveData()
        liveData.value = initValue
        return liveData
    }
    
    
    fun  LiveData.toNotNull(default: T): NotNullLiveData {
        val result = NotNullLiveData(default)
        result.addSource(this) {
            result.value = it ?: default
        }
        return result
    }
    

提交回复
热议问题