3

I have created a project with Jet-pack Navigation graph. In my project everything is working fine. But I am facing a problem that Suppose that We have 2 three fragment A and B. In Fragment A in the onViewCreated() method i call a API. Now I move From From Fragment A to B Using the action. it work fine but when i Go back to the Fragment B to A using popBackStack() or navigateUp() then the API of Fragment A is Again call.

So I Can't find the way that how can i save the state of the fragment and API will call only one time when the fragment is created first time. after that when we go back to the fragment then API will not call.

So Please suggest me that how can achieve this behaviour of fragment in the navigation graph.

sunil Kumawat
  • 475
  • 3
  • 14
  • I think that's how its suppose to work only the start destination is retained.. For rest you need to save your data in `ViewModel` in this case probably in a Shared One .. – ADM Jul 22 '22 at 05:17
  • 1
    @ADM - you don't need a shared ViewModel at all, just a ViewModel in Fragment A would be enough to only be created once (and hence, only run any APIs you call in your `ViewModel` creation once) even as the Fragment's view is created and destroyed as the fragment goes on the back stack. – ianhanniballake Jul 22 '22 at 05:29
  • Thx Ian u r right .. i misinterpreted the question .. I was thinking about preserving the fragment B's data which sounds dumb now .. – ADM Jul 22 '22 at 05:36
  • @ianhanniballake But is this possible to without model or any process by which we achieve this. – sunil Kumawat Jul 25 '22 at 05:14
  • `ViewModel` is the Key here .. why u need any other way ? Whatever class you use it has to be Scoped properly same as viewModelScope .. So better use ViewModel itself . If you are not using `ViewModel` the u need to edit your question with proper details . – ADM Jul 25 '22 at 07:01

0 Answers0