Reputation: 2731
I'm going through this tutorial
https://learntodroid.com/consuming-a-rest-api-using-retrofit2-with-the-mvvm-pattern-in-android/
and the user places the ViewModel Observer
inside onCreate
in the fragment. Why would I place it there when it's possible the data is done fetching, when the view hasn't been created yet?
For example:
//In fragment's onCreate
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getContext();
mListUsersAdapter = new MembersAdapter(mContext, mListUsers);
mViewModel = new ViewModelProvider(this).get(MembersViewModel.class);
mViewModel.init();
mViewModel.getMembersData().observe(this, new Observer<ResponseBody>() {
@Override
public void onChanged(ResponseBody responseBody) {
mListUsersAdapter.notifyDataSetChanged();
}
});
}
getMembersData()
may finish retrieving data and .notifyDataSetChanged()
would be called before onCreateView is called and the recycler created. Wouldn't it make more sense to place the observer in onCreateView
or even onViewCreated
?
Upvotes: 0
Views: 1795
Reputation: 96
To answer your question in a more general way, the problem you are describing could happened if your LiveData emits to an observer before the view is fully created.
To avoid such scenarios I would suggest using ViewLifecycleOwner and use it in lifecycle event such as onActivityCreated. There's this medium post you can check out to learn more.
Upvotes: 1
Reputation: 1282
In tutorial link they do search function. It do not have data until you click search button therefore it's ok to observe in onCreate. Depend on your logic you can observe in other place. Check this out
Upvotes: 1
Reputation: 1322
LiveData delivers updates only when data changes, and only to active observers.
He might have observe data in oncreate() to ensure that the fragment has data that it can display as soon as it becomes active. As soon as an app component is in the STARTED state, it receives the most recent value from the LiveData objects it’s observing. This only occurs if the LiveData object to be observed has been set.
Upvotes: 0