我有一个像下面这样的工作
job = GlobalScope.launch {
delay(5000)
runOnUiThread {
some unwanted code
}
}
该作业将等待5秒钟执行。并在5秒钟前取消通话
job?.cancel()
现在,有没有办法在5秒钟之前执行此作业?
我在寻找类似的东西,job?.forceExecute.ignoreDelays
或者job?.forceExecute.ignoreDelay("FirstDelay")
是否有类似名字的选项delay(5000,"FirstDelay")
这对我避免样板代码很有帮助。
我能想到的一种可能的解决方案是使用withTimeout而不是延迟,并在超时的情况下执行任务,您可以检查TimeoutCancellationException
GlobalScope.launch {
try {
withTimeout(5000){
//Imagine checkThisCondition() is a suspension function which will check the condition you need and return boolean
val condition : Boolean = checkThisCondition()
if(condition){
executeTheTask()
}
}
} catch (e : TimeoutCancellationException){
executeTheTask()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句