I recently started learning Android Architecture Components (LiveData, ViewModel and Navigation). So I created a bottom navigation application.
I am putting some sample code here just to talk about as an example.
SampleViewModel class:-
public class DashboardViewModel extends ViewModel {
private MutableLiveData<String> mText;
public DashboardViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is dashboard fragment");
}
public LiveData<String> getText() {
return mText;
}
}
SampleFragmentClass:-
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
final TextView textView = root.findViewById(R.id.text_dashboard);
dashboardViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
Let me be clear that there nothing wrong with these pieces of code.
I just want to ask some questions: -
Is the
ViewModelfully responsible for loading the data that will be used by an activity or a fragment?If I need to get some data from the server, would I call the API from
ViewModelor the activity itself?If I need to do some context-based actions, I would do that in the activity or a fragment. Is there some convention or guideline that I should do it in the ViewModel?
