将 MutableLiveData 公开为 LiveData 的正确方法? [英] Correct way to expose MutableLiveData as LiveData?

查看:25
本文介绍了将 MutableLiveData 公开为 LiveData 的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下公开MutableLiveData的方法:

方法A

class ThisViewModel : ViewModel() {私有 val _someData = MutableLiveData(true)val someData: LiveDataget() = _someData}//反编译的 Kotlin 字节码公共最终类 ThisViewModelDecompiled 扩展了 ViewModel {私有最终 MutableLiveData _someData = new MutableLiveData(true);@NotNull公共最终 LiveData getSomeData() {返回 (LiveData)this._someData;}}

方法 B

class ThatViewModel : ViewModel() {私有 val _someData = MutableLiveData(true)val someData: LiveData= _someData}//反编译的 Kotlin 字节码公共最终类 ThatViewModelDecompiled 扩展了 ViewModel {私有最终 MutableLiveData _someData = new MutableLiveData(true);@NotNull私有最终 LiveData someData;@NotNull公共最终 LiveData getSomeData() {返回 this.someData;}公共 ThatViewModel() {this.someData = (LiveData)this._someData;}}

<块引用>

是否有理由使用方法 B 而不是方法 A?

解决方案

Java 的角度来看,方法 A 在类中少了一个字段,因此是更多"高效的.从 Kotlin 的角度来看,方法 B 更清楚地表示,非可变属性是对可变属性的直接引用.此外,Kotlin 足够聪明,可以在本地访问该字段而不是 getter 方法.

<块引用>

是否有理由使用方法 B 而不是方法 A?

一般来说只是口味问题.从微观优化的角度来看,这取决于您是否也在类本身中使用此引用.

Consider the following ways to expose MutableLiveData:

Method 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;
   }
}

Method 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;
   }
}

Is there a reason to use Method B over Method A?

解决方案

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆