I have a single Activity
application with multiple Fragments
that are being switched by using Navigation components. When I switch between two fragments their onCreate()
and onDestroy()
methods seem to overlap. Thus making it difficult for me to write initialization and clean up code for fragments when they access the same global objects.
Navigating from Framgent_A
to Fragment_B
has the following order of methods:
Fragment_B.onCreate()
Fragment_A.onDestroy()
In Fragment_A.onDestroy()
I reverse the operations I do in Fragment_A.onCreate()
. And in Fragment_B
I expect things to be in a neutral state when onCreate()
is called. However that is not the case since Fragment_A.onDestroy()
has not yet been called.
Is the overlap normal on Android or did I configure something wrong in my Navigation components? Is there another way I could achieve what I am trying to do? I know I could couple both Fragments
and make it work, but I don't want either Fragment to know about each other. To me it seems weird that Framgnet_A
is still alive when Fragment_B
is created, when Fragment_B
is supposed to replace Fragment_A
.
Any help is greatly appreciated!
Edit:
After groing through the source code while debugging I have found out that in FragmentNavigator.navigate()
FragmentTransaction.setReorderingAllowed() is called, which allows reordering of operations, even allowing onCreate()
of a new fragment to be called before onDestroy()
of the previous. The question still remains, how can I solve my problem of correctly cleaning up global state in one Fragment before initializing the same global state in the next Fragment.