Skip to content

Instantly share code, notes, and snippets.

@joseprl89
Created May 27, 2018 18:06
Show Gist options
  • Save joseprl89/022c163f59381a74a9a1cac4123d5f63 to your computer and use it in GitHub Desktop.
Save joseprl89/022c163f59381a74a9a1cac4123d5f63 to your computer and use it in GitHub Desktop.
How LiveData is consumed for Internals of Android Architecture Components Part II- LiveData
public class NameViewModel extends ViewModel {
private MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<String>();
}
return mCurrentName;
}
}
public class NameActivity extends AppCompatActivity {
private NameViewModel mModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other code to setup the activity...
// Get the ViewModel.
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
// 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.
mNameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment