LiveData,how To Avoid The First Callback When Register Observer
I want to load tasks in a fragment, in fragment's onViewCreated,I register the LiveData
observer, in fragment's onResume,I load the task asynchronously, when first enter the fragment,it works fine,but when I navigate to other fragments then back to the task fragment, the callback onChanged()
will be called twice.
I know If LiveData already has data set, it will be delivered to the observer, so when back to the task fragment, onChanged
will be triggered when registering the observer in onViewCreated
, and in onResume, will trigger onChanged
the second time, I want to know how to avoid this. I have searched a lot, I know there is an EventWrapper
, which can mark the content consumed when onChanged triggered the first time. but I think this approach is too heavy. Sorry for my poor English...
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle
savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//...
mainViewModel = ViewModelProviders.of(getActivity()).get(MainViewModel.class);
mainViewModel.increaseTaskList.observe(getViewLifecycleOwner(), new
Observer<List<Task>>() {
@Override
public void onChanged(@Nullable List<Task> tasks) {
Log.d("ZZZ","data changed,IncreaseTaskListAdapter setData");
adapter.setData(tasks);
}
});
}
@Override
public void onResume() {
super.onResume();
mainViewModel.loadIncreasePointTaskList();
}
Answer
I found a simple solution,check the livedata value before load
@Override
public void onResume() {
super.onResume();
if (mainViewModel.increaseTaskList.getValue()==null) {
Log.d("ZZZ","IncreaseFragment loadTaskAsync");
mainViewModel.loadIncreasePointTaskList();
}
}
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View