Of course, we can not prevent calling oncrateView, but there is a simple way.
Instead of calling view.loadData() in onCreateView or other lifecycle methods we can call it while initializing ViewModel
this article helped me to know ViewModel better
5 common mistakes when using Architecture Components
Update:
The current navigation component (V 2.3.0) doesn't support this feature, it always kills the fragment while navigating to another fragment. Imagine you have google map in Fragment A so each time you returns to the Fragment it initialized again and the camera moves to the user location!! (what a bad idea).
So the best way is not to use the navigation component if you have the same issue.
Navigation, Saving fragment state, GitHub issue
Update 2:
In some cases like Filters or pagination, we can use Transformations like switchMap in our ViewModel instead of getting data in init function.
Update 3:
If you have to call a function to load data from a source, there are lots of ways to prevent call that function again, the first and easiest way is instead of calling getData() in your view, do it your ViewModel init function. the second one is using lazy variables and another one is using SwitchMap on livedata. for more information you can find all solutions here
ViewModel
+fragment.getViewLifecycleOwner()
. – MicrocircuitpopStackBack()
is called instead your old fragment will only get itsonResume()
called instead, else if it had been destroyed you need overrideonSaveInstanceState/onRestoreInstanceState
– Masseuse