Reputation: 8680
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?
Upvotes: 1
Views: 491
Reputation: 1006944
Please consider the following code from Google's Architecture Components tutorial:
That is not a tutorial. It is a reference with some code snippets, many of which will not compile, as they are there to illustrate syntax and call structure, not actually run.
Please note that LiveData objects are instantiated during declaration.
That is what the person who wrote that code snippet elected to do.
so Googles' recommendation is to instantiate them during declaration.
Google makes no such recommendation. The code snippet that you cite is an example, nothing more.
Why should LiveData objects be instantiated during declaration?
They do not have be fields with initializers. You are welcome to instantiate them in the constructor if you so choose. ViewModel
has specific rules about constructors (e.g., if you are not providing a factory, it needs to have a zero-argument constructor, or a one-Application
-argument constructor for AndroidViewModel
). But, other than that, you can do whatever you want.
It is frequently more concise to use an initializer — where the initializer is an available option — so there may be a tendency to use initalizers.
Upvotes: 1