0

I have an Android project where I'm using the Navigation Component to handle fragment navigation. In one of my fragments, I'm making an API call to fetch data and displaying it in the UI. However, whenever the user navigates back to this fragment using the back button, the whole fragment load again and API call is triggered again and the data is refreshed, causing unnecessary network requests and potential data inconsistencies.

I want to avoid this behavior and ensure that the fragment retains its state when the user navigates back. I don't want the API call to be made again and the data to be refreshed.

I've tried a few approaches, such as intercepting the back button press event, as well as using retainInstance = true and checking a flag to determine if the data has already been loaded. However, none of these solutions have worked for me.

Here is video of My Issue

https://drive.google.com/file/d/1dcy0AWtCknkxPNmUQ0N4Dqe9y6nTZcfq/view?usp=sharing

I guess issue with how i navigate fragment. Let me show you code

@AndroidEntryPoint
class SearchPhotosFragment : Fragment(R.layout.fragment_search_photos),
    SinglePhotoWallpaperClickListener {

    lateinit var fragmentSearchPhotosBinding: FragmentSearchPhotosBinding
    private val searchViewModel by activityViewModels<SearchViewModel>()
    private lateinit var singlePhotoListAdapter: SinglePhotoListAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        fragmentSearchPhotosBinding =
            FragmentSearchPhotosBinding.inflate(inflater, container, false)
        return fragmentSearchPhotosBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        fragmentSearchPhotosBinding.rvSearchPhotoPics.apply {
            layoutManager = LinearLayoutManager(requireContext())
            singlePhotoListAdapter = SinglePhotoListAdapter(this@SearchPhotosFragment)
            adapter = singlePhotoListAdapter
        }

        searchViewModel.userSearchQuery.observe(viewLifecycleOwner) {
            it?.let { query ->
                lifecycleScope.launch {
                    searchViewModel.searchPhotoList(query).collectLatest { photoList ->
                        Timber.d("photoList $photoList")
                        singlePhotoListAdapter.submitData(photoList)
                    }
                }
            }
        }

    }

    override fun homeWallpaperClick(urls: Urls, user: User, id: String) {
        findNavController().navigate(
            SearchFragmentDirections.actionSearchFragmentToWallpaperPreviewFragment(
                urls,
                user,
                id
            )
        )

    }
}

Here is link of full source code

https://github.com/PratikFagadiya/CatchyWall/tree/master

I would appreciate any guidance or suggestions on how to prevent the API call and data state saved refresh when the user navigates back using the Navigation Component. Thank you in advance!

Pratik Fagadiya
  • 1,195
  • 7
  • 21
  • When you navigate "back", you should use`findNavController().popBackStack()`, which pops the current fragment and bringing the previous fragment to the top of the stack. When you use `navigate`, a new fragment is created and added to the navigation stack, making "another" API call – gioravered May 24 '23 at 12:21
  • @gioravered I'm using system navigation but also tried with `findNavController().popBackStack()` and `findNavController().navigateUp()` but still same issue – Pratik Fagadiya May 24 '23 at 13:09
  • Can you call the API from your ViewModel's `init { }` method? – gioravered May 25 '23 at 06:35
  • Yes, but then issue is with recyclerview position – Pratik Fagadiya May 25 '23 at 10:43

0 Answers0