当应用程序从后台转到前台时,Android launchWhenResumed 不会被调用

Ma2*_*340 1 android android-lifecycle kotlin kotlin-coroutines

在我的片段中,

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()
    }
Run Code Online (Sandbox Code Playgroud)

以下是不同场景下的日志序列 -

  1. 当应用程序刚刚打开时 -

    视图内部已创建

    简历里面

    在生命周期范围内获取数据

  2. 当从一个片段回到这个片段时 -

    视图内部已创建

    简历里面

    在生命周期范围内获取数据

现在问题来了...

  1. 当应用程序从后台进入前台时 -

    简历里面

如您所见,我只看到onResume()日志,但我也希望日志Inside lifecyclescope get data出现。我在这里做错了什么吗?

lgv*_*lle 6

我相信你正在寻找的是Lifecycle.repeatOnLifecycle

    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                // Do stuff
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

更多信息: