将MutableLiveData公开为LiveData的正确方法? [英] Correct way to expose MutableLiveData as LiveData?
问题描述
请考虑以下公开MutableLiveData
的方法:
Consider the following ways to expose MutableLiveData
:
方法A
class ThisViewModel : ViewModel() {
private val _someData = MutableLiveData(true)
val someData: LiveData<Boolean>
get() = _someData
}
// Decompiled Kotlin bytecode
public final class ThisViewModelDecompiled extends ViewModel {
private final MutableLiveData _someData = new MutableLiveData(true);
@NotNull
public final LiveData getSomeData() {
return (LiveData)this._someData;
}
}
方法B
class ThatViewModel : ViewModel() {
private val _someData = MutableLiveData(true)
val someData: LiveData<Boolean> = _someData
}
// Decompiled Kotlin bytecode
public final class ThatViewModelDecompiled extends ViewModel {
private final MutableLiveData _someData = new MutableLiveData(true);
@NotNull
private final LiveData someData;
@NotNull
public final LiveData getSomeData() {
return this.someData;
}
public ThatViewModel() {
this.someData = (LiveData)this._someData;
}
}
是否有理由使用方法B而不是方法A?
Is there a reason to use Method B over Method A?
推荐答案
从 Java 角度来看,方法A 在类中的字段较少,因此""高效的.从 Kotlin 的角度来看,方法B 表示得更清楚一点,即非可变属性是对可变变量的直接引用.同样, Kotlin 足够聪明,可以本地访问该字段,而不是使用getter方法.
From the Java perspective, Method A has one less field in the class, thus is "more" efficient. From the Kotlin perspective, Method B denotes a bit more clearly, that the non-mutable property is a direct reference to the mutable one. Also Kotlin is clever enough to locally access the field rather than the getter method.
是否有理由使用方法B而不是方法A?
Is there a reason to use Method B over Method A?
通常只是口味问题.从微观优化的角度来看,它取决于您是否还要在类本身中使用此引用.
In general is merely a matter of taste. Looking at it from a micro-optimization perspective it depends on whether or not you'd also use this reference within the class itself.
这篇关于将MutableLiveData公开为LiveData的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!