android - 将 MutableLiveData 公开为 LiveData 的正确方法?
问题描述
考虑以下公开方式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?
解决方案
从Java的角度来看,方法 A在类中少了一个字段,因此“更”高效。从Kotlin的角度来看,方法 B更清楚地表示,非可变属性是对可变属性的直接引用。Kotlin也很聪明,可以在本地访问字段而不是 getter 方法。
是否有理由使用方法 B 而不是方法 A?
一般来说,只是口味问题。从微优化的角度来看,这取决于您是否还会在类本身中使用此引用。
推荐阅读
- linux - ASP.NET Core:运行依赖于框架的应用程序时“找不到框架‘Microsoft.AspNetCore.App’,版本‘3.1.0’”
- r - 使用 dplyr 比较组并过滤常见的观察结果
- r - 使用 dplyr 将一组中缺少的级别添加到汇总表
- python - 如何从每类 imagenet 中获取 50 个样本?
- wpf - UserControl 'Loaded' 上的 EventTrigger 未调用 ICommand.Execute
- c - 为什么我没有得到正确的总和值?
- dependency-injection - CDI注入具体接口实现
- reactjs - 在标签旁边创建 MUI 文本字段
- ansible - 如何在具有 python 2.4 的远程服务器上进行 ansible 工作
- javascript - 所需的 JSON 文件具有运行程序之前的旧值