kotlin 协程无法启动

问题描述 投票:0回答:1

!当我的片段转到系统后面时,它调用 onStop()。然后当我的片段转到系统前部时,它调用 onResume()。但 mainViewModelScope 不会启动协程。 我的片段

    override fun onResume() {
        super.onResume()
        Log.d("aaaa", "resume========")
        viewModel.startFetchDeviceTimer()
    }

    override fun onStop() {
        super.onStop()
        Log.d("aaaa", "stop========")
        viewModel.cancelFetchDeviceTimer()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("aaaa", "destroy========")
    }

我的视图模型

    private val mainViewModelScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    fun startFetchDeviceTimer() {
        startTimerActual()
    }

    private fun startTimerActual() {
         // launchWithVM({
        mainViewModelScope.launch {
            while (isActive) {
                Log.d(TAG, Thread.currentThread().name)
                // 网络请求异步任务在IO线程的协程中
                ioScope.launch {
                    Log.d(TAG, Thread.currentThread().name)
                    val deviceResponse = homeRepository.getDeviceList()
                    val deviceVOList = deviceResponse.deviceList.map { deviceModel ->
                        mapModel2VO(deviceModel)
                    }
                    deviceVOListData.postValue(deviceVOList)
                }
                delay(FETCH_DEVICE_INTERVAL.toDuration(DurationUnit.SECONDS))
            }
        }
        // }, {})
    }

我希望 mainViewModelScope 在我的片段进入系统前部时启动一个协程。我怎样才能做到这一点

android kotlin android-lifecycle coroutine polling
1个回答
0
投票

我测试了你的代码,它工作正常。 mainViewModelScope 将在每次调用 onresume 时运行。如果您在 onStop() 中取消 mainViewModelScope,则可以将其删除。请检查

viewModel.cancelFetchDeviceTimer()
© www.soinside.com 2019 - 2024. All rights reserved.