Reputation: 14144
In the Google's example ViewModels
changes are observed using
model.getUsers().observe(this, users -> {
// update UI
});
The --> {}
pattern is a Java 8 lambda-functions feature. users
is undefined in this case. Also Studio shows mismatch error, since Observer<your_type>
is expected as the 2nd parameter.
According to the reference:
void observe(LifecycleOwner owner, Observer observer) Adds the given observer to the observers list within the lifespan of the given owner.
So the code supposed to be something like:
class Observer FooObserver() {
@Override
public function onChanged(...
}
..
fooObserver = new FooObserver(..
..
model.getUsers().observe(this, fooObserver);
Question:
Is this supposed to be some kind of abstract example or do this shortcut code really suppose to replace Observer
usage?
Upvotes: 1
Views: 987
Reputation: 2256
This is just a short form for inner observer implementation.
So this
model.getUsers().observe(this, users -> {
// update UI
});
Is equal to this
model.getUsers().observe(this, new Observer<User>() {
@Override
public void onChanged(User user) {
}
});
You can integrate lambda expressions and some of the other java8 features into your projects using Retrolambda.
Upvotes: 2