'Android launchWhenResumed is not called when the app comes to foreground from background

In my fragment,

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

        Log.e(TAG, "Inside on view created")

        lifecycleScope.launchWhenResumed {
            Log.e(TAG, "Inside lifecyclescope get data")
            viewModel.getData().collect {
              // ....
            
            }
        }
    }

    override fun onResume() {
        Log.e(TAG, "Inside on resume")
        super.onResume()
    }

Here are the log sequences in different scenarios -

  1. When App opened freshly -

    Inside on view created

    Inside on resume

    Inside lifecyclescope get data

  2. When coming back from a fragment to this fragment -

    Inside on view created

    Inside on resume

    Inside lifecyclescope get data

Now comes the problem...

  1. When the app comes to foreground from the background -

    Inside on resume

As you see, I only see the onResume() log but I also expect the log Inside lifecyclescope get data to appear. Am I doing anything wrong here?



Solution 1:[1]

I believe what you are looking for is Lifecycle.repeatOnLifecycle

    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                // Do stuff
            }
        }
    }

More info:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lgvalle