其他分享
首页 > 其他分享> > android – 将MutableLiveData公开为LiveData的正确方法?

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

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

解决方法:

从Java的角度来看,方法A在类中只有一个字段,因此“更有效”.从Kotlin的角度来看,方法B更清楚地表示,非可变属性是对可变属性的直接引用. Kotlin也非常聪明,可以在本地访问该字段而不是getter方法.

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

一般来说,仅仅是品味问题.从微观优化的角度来看,它取决于你是否也在课堂内使用这个参考.

标签:android,kotlin,android-livedata
来源: https://codeday.me/bug/20191008/1871426.html