[英]How to start a coroutine on main thread without using GlobalScope?
[英]how to avoid using GlobalScope
在我的代码中,我有一个超时功能,我想使用倒数计时器,但经过大量研究,我在 Kotlin 协程中找不到与倒数计时器类似的功能(能够启动、取消和捕获完成回调)。 然后我决定使用GlobalScope.launch
。 我知道这是一个糟糕的解决方案,但我的代码运行良好。
这是我的代码
viewModelScope.launch {
val timer = object: CountDownTimer(Constants.PAYMENT_TIMER, 1000) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
GlobalScope.launch {
_eventFlow.emit(UIPaymentEvent.NavigateToBack)
}
}
}
timer.start()
collectPaymentIntentUseCase.invoke(currentPaymentIntent!!).onEach { result ->
when (result) {
is Resource.Success -> {
timer.cancel()
if (result.data?.exception == null) {
我的问题是如何找到 100% 相似的 function 以避免使用 GlobalScope 但能够使用倒数计时器(启动、取消、onComplete 回调)?
注意:我使用 GlobalScope.lanch 能够向我的视图发出 UIPaymentEvent.NavigateToBack 事件
您在这里不需要CountDownTimer
。 只需使用delay()
暂停 function。
viewModelScope.launch {
val job = launch {
delay(Constants.PAYMENT_TIMER) // Wait for timeout
_eventFlow.emit(UIPaymentEvent.NavigateToBack)
}
collectPaymentIntentUseCase.invoke(currentPaymentIntent!!).onEach { result ->
when (result) {
is Resource.Success -> {
job.cancel() // Cancel the timer
if (result.data?.exception == null) {
您的问题有些不清楚,请尝试添加更多详细信息,您实际上想要实现什么以及您面临的错误是什么。
您可以使用callbackFlow
来监听您的计时器。 我只是编写这个编辑器。 我希望它会有所帮助。
fun timerFlow() = callbackFlow<UIPaymentEvent> {
val timer = object : CountDownTimer(10, 1000) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
CoroutineScope().launch {
_eventFlow.emit(UIPaymentEvent.NavigateToBack)
}
}
}
timer.start()
awaitClose()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.