Kotlin的可空性和LiveData [英] Nullability and LiveData with Kotlin
本文介绍了Kotlin的可空性和LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将LiveData与Kotlin一起使用,并且其值不能为null.您如何处理?也许是LiveData的包装?在这里搜索良好的模式.. 例如:
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 an example:
class NetworkDefinitionProvider : MutableLiveData<NetworkDefinition>() {
val allDefinitions = mutableListOf(RinkebyNetworkDefinition(), MainnetNetworkDefinition(), RopstenNetworkDefinition())
init {
value = allDefinitions.first()
}
fun setCurrent(value: NetworkDefinition) {
setValue(value)
}
}
我知道访问时值不会为空-但我将始终必须检查是否为空或这些丑陋的!!周围.
I know value will not be null when accessing - but I will always have to check for null or have these ugly !!'s around.
推荐答案
我创建了扩展属性.它不是很漂亮,但是 很简单.
I created an extension property. It's not super pretty, but it is pretty straightforward.
val <T> LiveData<T>.valueNN
get() = this.value!!
用法
spinner.loading = myLiveData.valueNN.homeState.loading
我不愿意将"NN"作为良好的命名约定,但这超出了问题的范围:)
I'm not sold on appending "NN" as a good naming convention, but that's beyond the scope of the question :)
这篇关于Kotlin的可空性和LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文