Please consider the following code from Google's Architecture Components tutorial:
class MyViewModel extends ViewModel {
private final PostalCodeRepository repository;
private final MutableLiveData<String> addressInput = new MutableLiveData();
public final LiveData<String> postalCode =
Transformations.switchMap(addressInput, (address) -> {
return repository.getPostCode(address);
});
public MyViewModel(PostalCodeRepository repository) {
this.repository = repository
}
private void setInput(String address) {
addressInput.setValue(address);
}
}
Please note that LiveData
objects are instantiated during declaration.
From what I can tell from this answer, there is very little difference difference between instantiating them during declaration or inside of a constrictor. Yet, from what I understand, there is a possibility of having NPE
s or having stale references when LiveData
objects are instantiated through a constructer, so Googles' recommendation is to instantiate them during declaration.
My hunch is that it may have something to do with creating ViewModel
objects through reflection, however I have been unable to find how exactly it could effect creation of those objects.
Why should LiveData
objects be instantiated during declaration?