Nullability and LiveData with Kotlin

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

    I don't know if this is the best solution but this is what I came up with and what I use:

    class NonNullLiveData(private val defaultValue: T) : MutableLiveData() {
    
        override fun getValue(): T = super.getValue() ?: defaultValue
    
        fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
            observe(owner, Observer {
                body(it ?: defaultValue)
            })
        }
    }
    

    Creating the field:

    val string = NonNullLiveData("")
    

    And observing it:

    viewModel.string.observe(this) {
        // Do someting with the data
    }
    

提交回复
热议问题