I realize there is a significant different, when using lambda and anonymous class to observe LiveData
Anonymous class
button.setOnClickListener(e -> {
mainViewModel.getCounter().observe(MainFragment.this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer counter) {
android.util.Log.i("CHEOK", "Observer 3 : " + counter + ", " + this);
}
});
});
Lamda
button.setOnClickListener(e -> {
mainViewModel.getCounter().observe(MainFragment.this, counter -> {
android.util.Log.i("CHEOK", "Observer 3 : " + counter);
});
});
When you click on the button multiple times, for anonymous class, multiple different instances of observes will be created, and passed to LiveData
. Hence, if you press the button 3 times, and execute
counter.postValue(counter.getValue());
You will get
Observer 3 : 123, com.xxx.MainFragment$1@cd023a
Observer 3 : 123, com.xxx.MainFragment$1@beb52e1
Observer 3 : 123, com.xxx.MainFragment$1@d1ffcf4
But for lamda, even if you press the button multiple times, only a single instance of Observer will ever be created. You will only get
Observer 3 : 123
Android guideline doesn't specifically mentions such catch. I was wondering, should we be using Anonymous class
, or Lambda
to observe LiveData
?