voben
11/05/2019, 6:31 PMval myLiveData: LiveData<String> = _backingLiveData
val myLiveData2: LiveData<String>
get() = _backingLiveData
Casey Brooks
11/05/2019, 6:33 PMJohn
11/05/2019, 9:43 PMfun getMyLiveData(): LiveData<String> {
return _backingLiveData
}
arekolek
11/05/2019, 11:29 PMThe first one caches the value in a backing field, and is executed once at object creation. The second one does not have a backing field, is lazily evaluated, and gets executed on each accessThat’s not a good way of looking at it. It makes it sound like the first one is better, while it’s not. See https://kotlinlang.org/docs/reference/properties.html#backing-properties Here’s the decompiled bytecode for that example:
private final MutableLiveData<String> _backingLiveData = new MutableLiveData<>();
private final LiveData<String> myLiveData = _backingLiveData;
public final LiveData<String> getMyLiveData() {
return myLiveData;
}
public final LiveData<String> getMyLiveData2() {
return _backingLiveData;
}
You can see that myLiveData
uses more memory, but doesn’t have any performance benefit.nrobi
11/06/2019, 9:04 AMproguard/R8
, the first option may be still optimized