Class ViewModel
Fragment
.
It also handles the communication of the Fragment with the rest of the application
(e.g. calling the business logic classes).
A ViewModel is always created in association with a scope (a fragment) and will be retained as long as the scope is alive.
In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. density / view scale). The new owner instance just re-connects to the existing model.
The purpose of the ViewModel is to acquire and keep the information that is necessary
for a Fragment. The Fragment should be able to observe changes in the ViewModel.
ViewModels usually expose this information via LiveData
or Two-Way Data
Binding. You can also use any observability construct from your favorite framework.
ViewModel's only responsibility is to manage the data for the UI. It should never access your view hierarchy or hold a reference back to the Fragment.
ViewModels can be used as a communication layer between different Fragments. Each Fragment can acquire the ViewModel using the same key. This allows communication between Fragments in a de-coupled fashion such that they never need to talk to the other Fragment directly.
public class MyFragment extends Fragment {
@Override
public void onCreate(@Nullable DataSet savedInstanceState) {
super.onCreate(savedInstanceState);
final UserModel userModel = new ViewModelProvider(this).get(UserModel.class);
userModel.getUser().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User data) {
// update ui.
}
});
findViewById(R.id.button)
.setOnClickListener(v -> userModel.doAction());
}
}
ViewModel would be:
public class UserModel extends ViewModel {
private final MutableLiveData<User> userLiveData = new MutableLiveDat<>();
public LiveData<User> getUser() {
return userLiveData;
}
public UserModel() {
// trigger user load.
}
void doAction() {
// depending on the action, do necessary business logic calls and update the
// userLiveData.
}
}
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionprotected void
This method will be called when this ViewModel is no longer used and will be destroyed.
-
Constructor Details
-
ViewModel
public ViewModel()
-
-
Method Details
-
onCleared
protected void onCleared()This method will be called when this ViewModel is no longer used and will be destroyed.It is useful when ViewModel observes some data, and you need to clear this subscription to prevent a leak of this ViewModel.
-