0

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 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

If there are multiple TextViews then there will that many observers,right? Also in "someMethod" , I dont understand the use of different threads,if you can then kindly explain. Thanks
On main thread(default UI thread) use setValue, for non-main thread use postValue. About observers: if values of some textView depends on one source of data(can be array like MutableLiveData<ArrayList<Object>>) then you can create one observer. Otherwise make more. In my real project atm i have 5 observers in one fragment, one of them is observing some position(int value) from viewModel and changes 5 views(textViews, imageViews etc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.