Kotlin 协程在修改后的实时数据中使用<Boolean>。运行计数器并取消它



我需要你的帮助,有一个livedata返回一个不断变化的布尔值。我需要的是,当为true时,协同程序被执行(只是模仿加载百分比从0到100%),分别,false取消它,以此类推。

如果返回true,则运行协程,否则取消它

graphicOverlay.onSuccess.observe(viewLifecycleOwner, {
auraImageView.isInvisible = it != true
noteScanFaceView.isVisible = it == false
if (!isFaceDetected) {
if (it) {
buttonChangeCameraSelector.isVisible = false
llScanning.isVisible = true
viewLifecycleOwner.lifecycleScope.launch {counter()}
isFaceDetected = true
} else {
viewLifecycleOwner.lifecycleScope.cancel()
}
}
})

这是一个计数器

private suspend fun counter() = viewLifecycleOwner.lifecycleScope.launch {
val job = launch {
while (progressStatus < 100) {
progressStatus += 1
delay(50)
handler.post {
textViewPercent.text = "$progressStatus"
}
}
}
job.join()
fragmentSendDataListener.onSendResultsModel(resultSendData)
requireActivity().runOnUiThread {
llToolbar.isVisible = false
}
}

你必须重新定义你的计数器,你启动一个协程,它启动一个协程,这个协程可以变成一个协程。为了取消一个协程你必须让它可协同取消.

private suspend fun counter() {
while (coroutineContext.isActive && progressStatus < 100) {
progressStatus += 1
delay(50)
handler.post {
textViewPercent.text = "$progressStatus"
}
}
fragmentSendDataListener.onSendResultsModel(resultSendData)
requireActivity().runOnUiThread {
llToolbar.isVisible = false
}
}

由于launch返回一个作业,因此保留对它的引用,并将其重新定义/取消为需要的。

private var counterJob: Job? = null
graphicOverlay.onSuccess.observe(viewLifecycleOwner, {
auraImageView.isInvisible = it != true
noteScanFaceView.isVisible = it == false
if (!isFaceDetected) {
if (it) {
buttonChangeCameraSelector.isVisible = false
llScanning.isVisible = true
counterJob = viewLifecycleOwner.lifecycleScope.launch {counter()}
isFaceDetected = true
} else counterJob?.cancel()
}
})

launch返回一个Job,您可以取消它而不是整个协程作用域。

所以我要做如下的事情:

  1. 保存对计数器作业的引用:private var counterJob: Job? = null
  2. 需要时更新:counterJob = launch { counter() }
  3. 需要时取消:counterJob?.cancel()

最新更新