首页 > 解决方案 > 将 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?

标签: androidkotlinandroid-livedata

解决方案


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

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

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


推荐阅读