Kotlin 的可空性和 LiveData
Nullability and LiveData with Kotlin
我想将 LiveData 与 Kotlin 一起使用,并且具有不应该为 null 的值。你如何处理这个问题?也许是 LiveData 的包装器?在这里寻找好的模式..
例如:
class NetworkDefinitionProvider : MutableLiveData<NetworkDefinition>() {
val allDefinitions = mutableListOf(RinkebyNetworkDefinition(), MainnetNetworkDefinition(), RopstenNetworkDefinition())
init {
value = allDefinitions.first()
}
fun setCurrent(value: NetworkDefinition) {
setValue(value)
}
}
我知道访问时值不会为 null - 但我总是必须检查 null 或周围有这些丑陋的 !!。
我创建了一个扩展 属性。它不是很漂亮,但非常简单。
val <T> LiveData<T>.valueNN
get() = this.value!!
用法
spinner.loading = myLiveData.valueNN.homeState.loading
我不同意附加 "NN" 作为一个好的命名约定,但这超出了问题的范围:)
我不知道这是否是最好的解决方案,但这是我想到的和我使用的:
class NonNullLiveData<T>(private val defaultValue: T) : MutableLiveData<T>() {
override fun getValue(): T = super.getValue() ?: defaultValue
fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
observe(owner, Observer<T> {
body(it ?: defaultValue)
})
}
}
创建字段:
val string = NonNullLiveData("")
并观察它:
viewModel.string.observe(this) {
// Do someting with the data
}
我对 The Lucky Coder 的改进不大。此实现根本无法接受空值。
class NonNullMutableLiveData<T: Any>(initValue: T): MutableLiveData<T>() {
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> { t -> body(t!!) })
}
override fun postValue(value: T) {
super.postValue(value)
}
}
您可以为 LifecycleOwner 创建一个扩展
fun <T> LifecycleOwner.observe(liveData: LiveData<T?>, lambda: (T) -> Unit) {
liveData.observe(this, Observer { if (it != null) lambda(it) })
}
然后在你的 fragment/activity
observe(liveData) { ... }
你可以做到这一点
normalLiveData
.nonNull()
.observe(this, { result ->
// result is non null now
})
有一篇关于它的文章。 https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333
这是我的解决方案。
class NotNullLiveData<T : Any>
constructor(private val default: T) : MediatorLiveData<T>() {
override fun getValue(): T {
return super.getValue() ?: default
}
override fun setValue(value: T) {
super.setValue(value)
}
}
@MainThread
fun <T : Any> mutableLiveDataOfNotNull(initValue: T): NotNullLiveData<T> {
val liveData = NotNullLiveData(initValue)
liveData.value = initValue
return liveData
}
@MainThread
fun <T> mutableLiveDataOf(initValue: T): MutableLiveData<T> {
val liveData = MutableLiveData<T>()
liveData.value = initValue
return liveData
}
fun <T : Any> LiveData<T?>.toNotNull(default: T): NotNullLiveData<T> {
val result = NotNullLiveData(default)
result.addSource(this) {
result.value = it ?: default
}
return result
}
使用这种方式使用字符串很简单:
val someLiveData = MutableLiveData<String>()
...
someLiveData.value.orEmpty()
如果设置或空字符串而不是 null
,您将获得实际值。
我真的很喜欢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指点):
class NonNullLiveData<T>(private val defaultValue: T) : MutableLiveData<T>() {
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<T> {
body(it ?: defaultValue)
})
}
}
现在 MutableLiveData 中的值永远不会为 null,因此 class 不会以非预期的方式使用。
我想将 LiveData 与 Kotlin 一起使用,并且具有不应该为 null 的值。你如何处理这个问题?也许是 LiveData 的包装器?在这里寻找好的模式.. 例如:
class NetworkDefinitionProvider : MutableLiveData<NetworkDefinition>() {
val allDefinitions = mutableListOf(RinkebyNetworkDefinition(), MainnetNetworkDefinition(), RopstenNetworkDefinition())
init {
value = allDefinitions.first()
}
fun setCurrent(value: NetworkDefinition) {
setValue(value)
}
}
我知道访问时值不会为 null - 但我总是必须检查 null 或周围有这些丑陋的 !!。
我创建了一个扩展 属性。它不是很漂亮,但非常简单。
val <T> LiveData<T>.valueNN
get() = this.value!!
用法
spinner.loading = myLiveData.valueNN.homeState.loading
我不同意附加 "NN" 作为一个好的命名约定,但这超出了问题的范围:)
我不知道这是否是最好的解决方案,但这是我想到的和我使用的:
class NonNullLiveData<T>(private val defaultValue: T) : MutableLiveData<T>() {
override fun getValue(): T = super.getValue() ?: defaultValue
fun observe(owner: LifecycleOwner, body: (T) -> Unit) {
observe(owner, Observer<T> {
body(it ?: defaultValue)
})
}
}
创建字段:
val string = NonNullLiveData("")
并观察它:
viewModel.string.observe(this) {
// Do someting with the data
}
我对
class NonNullMutableLiveData<T: Any>(initValue: T): MutableLiveData<T>() {
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> { t -> body(t!!) })
}
override fun postValue(value: T) {
super.postValue(value)
}
}
您可以为 LifecycleOwner 创建一个扩展
fun <T> LifecycleOwner.observe(liveData: LiveData<T?>, lambda: (T) -> Unit) {
liveData.observe(this, Observer { if (it != null) lambda(it) })
}
然后在你的 fragment/activity
observe(liveData) { ... }
你可以做到这一点
normalLiveData
.nonNull()
.observe(this, { result ->
// result is non null now
})
有一篇关于它的文章。 https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333
这是我的解决方案。
class NotNullLiveData<T : Any>
constructor(private val default: T) : MediatorLiveData<T>() {
override fun getValue(): T {
return super.getValue() ?: default
}
override fun setValue(value: T) {
super.setValue(value)
}
}
@MainThread
fun <T : Any> mutableLiveDataOfNotNull(initValue: T): NotNullLiveData<T> {
val liveData = NotNullLiveData(initValue)
liveData.value = initValue
return liveData
}
@MainThread
fun <T> mutableLiveDataOf(initValue: T): MutableLiveData<T> {
val liveData = MutableLiveData<T>()
liveData.value = initValue
return liveData
}
fun <T : Any> LiveData<T?>.toNotNull(default: T): NotNullLiveData<T> {
val result = NotNullLiveData(default)
result.addSource(this) {
result.value = it ?: default
}
return result
}
使用这种方式使用字符串很简单:
val someLiveData = MutableLiveData<String>()
...
someLiveData.value.orEmpty()
如果设置或空字符串而不是 null
,您将获得实际值。
我真的很喜欢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指点):
class NonNullLiveData<T>(private val defaultValue: T) : MutableLiveData<T>() {
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<T> {
body(it ?: defaultValue)
})
}
}
现在 MutableLiveData 中的值永远不会为 null,因此 class 不会以非预期的方式使用。