What’s the difference between creating a property with a getter function vs one without. Are these 2 actually the same thing?
Copy code
val myLiveData: LiveData<String> = _backingLiveData
val myLiveData2: LiveData<String>
get() = _backingLiveData
c
Casey Brooks
11/05/2019, 6:33 PM
The 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 access
fun getMyLiveData(): LiveData<String> {
return _backingLiveData
}
a
arekolek
11/05/2019, 11:29 PM
The 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 access
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.