I am bit stuck at understanding the relation b/w using viewmodel and livedata. I hope that someone can explain it for me. I am new to Android Development.
2 Answers
It's all well explained here. The ViewModel purpose is to manipulate the data so to provide the data needed to the view, like in any normal mvp pattern. LiveData instead is the (lifecycle aware) callback for the view model, so that any time the data set is updated (so the model has a potential change in its state), the execution flow is brought back to the model, so that the model can update itself, for instance manipulate the new data set before to provide it to the view. I hope it's clear
Comments
For MVVM architecture it looks like this: you create model with your data, you access and change it in view model(in instances of LiveData). And observe it in views(activities/fragments).
MainViewModel extends ViewModel{
MutableLiveData<String> someStringObject = new MutableLiveData<>;
private void someMethod{
someStringObject.setValue("For main thread");
someStringObject.postValue("For back thread");
}
public MutableLiveData<String> getSomeStringObject(){
return someStringObject;
}
}
FragmentA extends Fragment{
@BindView(R.id.tv) //ButterKnife
TextView someTV;
private MainViewModel mainViewModel;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
//getting viewModel
mainViewModel = ViewModelProviders.of(getActivity()).get(MainViewModel.class);
//registering observer
mainViewModel.getSomeStringObject.observe(this, value ->{
someTV.setText(value);
});
}
}
This way you can react to changes of ViewModel in your View. Now if getSomeStringObject is changed in mainViewModel it will automatically change in FragmentA.