is an interface for objects with a Lifecycle LifecycleObserver is as interface for observing a LifecycleOwner Lifecycle-Aware Components Fragments and Activities in Support Library 26.1.0 and later already implement the LifecycleOwner interface.
myLocationListener = new MyLocationListener(this, (location) -> { // update UI }); } @Override public void onStart() { myLocationListener.start(); // manage other components that need to respond to the activity lifecycle } @Override public void onStop() { myLocationListener.stop(); // manage other components that need to respond to the activity lifecycle }
extends AppCompatActivity { @Override public void onStart() { super.onStart(); Util.checkUserStatus(result -> { // what if this callback is invoked AFTER activity is stopped? if (result) { myLocationListener.start(); } }); }
Lifecycle events @OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { if (enabled) { // connect } } public void enable() { enabled = true; //Query the current state of the Lifecycle if (lifecycle.getCurrentState().isAtLeast(STARTED)) { // connect if not connected } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { // disconnect if connected } }
public void onCreate(LifecycleOwner owner) { // your code } } public interface DefaultLifecycleObserver extends FullLifecycleObserver { //provides default implementation for all 6 FullLifecycleObserver methods @Override default void onCreate(@NonNull LifecycleOwner owner) { } } If you use Java 8 language, always prefer it over annotations.
Only notifies active observers about updates • The Room persistence library supports observable queries, which return LiveData objects Observer • A simple callback that can receive from LiveData
hold a certain type of data. This is usually done within your ViewModel class • Create an Observer object that defines the onChanged() method (usually done in a UI controller, such as an activity or fragment) • Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object
Create a LiveData with a String private MutableLiveData<String> mCurrentName; public MutableLiveData<String> getCurrentName() { if (mCurrentName == null) { mCurrentName = new MutableLiveData<String>(); } return mCurrentName; } // Rest of the ViewModel... }
// Create the observer which updates the UI final Observer<String> nameObserver = new Observer<String>() { @Override public void onChanged(@Nullable final String newName) { // Update the UI, in this case, a TextView nameTextView.setText(newName); } }; // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer viewModel.getCurrentName().observe(this, nameObserver);
v) { String anotherName = "John Doe"; viewModel.getCurrentName().setValue(anotherName); } }); liveData.postValue("a"); //call it from a worker thread liveData.setValue("b"); //call it from a main thread
output • switchMap() - apply function that swaps LiveData observer it is listening to • MediatorLiveData - LiveData with multiple sources for custom transformations
dispatches the result to its observers, giving you the opportunity to manipulate the data value. LiveData<User> userLiveData = ...; LiveData<String> userName = Transformations.map(userLiveData, user -> { user.name + " " + user.lastName });
the LiveData object. The function passed to switchMap() must return a LiveData object MutableLiveData<String> userIdLiveData = ...; LiveData<User> userLiveData = Transformations.switchMap(userIdLiveData, id -> repository.getUserById(id)); void setUserId(String userId) { this.userIdLiveData.setValue(userId); }
savedInstanceState) { // Create a ViewModel the first time the system calls an activity's onCreate() method. // Re-created activities receive the same MyViewModel instance created by the first activity. MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class); viewModel.getUsers().observe(this, users -> { // update UI }); } }
or any class that may hold a reference to the activity context. AndroidViewModel is Application context aware ViewModel AndroidViewModel subclasses must have a constructor which accepts Application as the only parameter.
private final MutableLiveData<Item> selected = new MutableLiveData<Item>(); public void select(Item item) { selected.setValue(item); } public LiveData<Item> getSelected() { return selected; } } //Fragments can share a ViewModel using their activity scope SharedViewModel viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);