androidkotlinandroid-lifecyclecoroutinepolling

kotlin-coroutine can not be launched


when my fragment go backgroud of system, it invoke onStop().and then when my fragment go front desk of system, it invoke onResume(). but mainViewModelScope does not lanuch a coroutine.

my fragment

    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========")
    }

my viewModel

    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))
            }
        }
        // }, {})
    }

    fun cancelFetchDeviceTimer() {
        if (mainViewModelScope.isActive) {
            mainViewModelScope.cancel()
        }
    }

I want mainViewModelScope to lanuch a coroutine when my fragment go front desk of system. How can i do that?


Solution

  •  viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                viewModel.startFetchDeviceTimer()
            }
        }