Skip to content Skip to sidebar Skip to footer

How To Cancel Collect Coroutine Stateflow?

I have collect flow from shared viewmodel in fragment : private val viewModel: MyViewModel by sharedViewModel() private fun observeViewModelStateFlowData() { job = lifecycleScope.

Solution 1:

Well you have to know something about coroutine. If we just call cancel, it doesn’t mean that the coroutine work will just stop. If you’re performing some relatively heavy computation, like reading from multiple files, there’s nothing that automatically stops your code from running.

You need to make sure that all the coroutine work you’re implementing is cooperative with cancellation, therefore you need to check for cancellation periodically or before beginning any long running work. Try to add check before handling a result.

job = lifecycleScope.launch {
            viewModel.stateFlowData.collect {
                ensureActive()
                when (it) {
                    is ViewStates.Success -> handleSuccess(it.data)
                }
            }
        }
    }

For more info take a look on this article https://medium.com/androiddevelopers/cancellation-in-coroutines-aa6b90163629

Post a Comment for "How To Cancel Collect Coroutine Stateflow?"