you ◦ Separation of concerns ◦ Testable ◦ Consistent ◦ <insert your goal here> • Implement it using Architecture Components ◦ Solve common Android problems ◦ Pick and choose the ones you need
public MyLocationListener(Lifecycle lifecycle, Callback callback) { mLifecycle = lifecycle; lifecycle.addObserver(this); } public void enable() { if (mLifecycle.getCurrentState().isAtLeast(Lifecycle.State.STARTED)) { // do things } else { // defer things } } }
observe it • Annotate methods with @OnLifecycleEvent • Easy to check current state and compare it • Components are self-contained, Activity boilerplate reduced!
LocationLiveData locationLiveData = new LocationLiveData(); // Automatically unregistered when the activity is destroyed // If this has an initial value, it won't be delivered yet! locationLiveData.observe(this, this::handleLocation); } private void handleLocation(Location location) { // won't receive any callbacks until the activity is started or resumed }
void onActive() { startListeningForLocation(); } @Override protected void onInactive() { stopListeningForLocation(); } @Override public void onLocationChanged(Location location) { // this value will be cached and delivered to all observers setValue(location); } }
{ super.onCreate(savedInstanceState); // The Activity acts as the scope. // If the model does not exist in this scope, it’s created. // Otherwise the existing model is returned MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class); model.getUsers().observe(this, users -> { // update UI }); } }