4. * Taken from the book O'Reilly Head First "Design Patterns"
The one who is listening is Observer...
And the other one, who is emitting events, is subject or observable.
5. LiveData
public LiveData<Films> getFilms() {
final MutableLiveData<Films> data = new MutableLiveData<>();
webService.getFilms().enqueue(new Callback<Films>() {
@Override
public void onResponse(Call<Films> call, Response<Films> response) {
data.setValue(response.body());
}
});
return data;
}
// Update the list when the data changes
viewModel.getFilms().observe(this, new Observer<Films>() {
@Override
public void onChanged(@Nullable Films films) {
if (films != null) {
lstFilms.setAdapter(new FilmsAdapter(getApplicationContext(), films.results);
}
});
7. ViewModel
The ViewModel class is designed to store and manage UI-related
data so that the data survives configuration changes such as
screen rotations.
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<Users>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// do async operation to fetch users
}
}
public void onCreate(Bundle savedInstanceState) {
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
}
8. Handling Lifecycle
The android.arch.lifecycle package provides classes and interfaces that let
you build lifecycle-aware components — which are components that can
automatically adjust their behavior based on the current lifecycle of an
activity or fragment
9. LifecycleOwner
LifecycleOwner is a single method interface that denotes that the class has a
Lifecycle. It has one method, getLifecycle(), which must be implemented by the
class.
public class MyFragment extends Fragment implements LifecycleRegistryOwner {
LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
@Override
public LifecycleRegistry getLifecycle() {
return lifecycleRegistry;
}
}
10. LifecycleObserver
LifecycleObserver observe LifecycleOwners, and are notified of lifecycle changes.
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
}
}
aLifecycleOwner.getLifecycle().addObserver(new MyObserver());