假设我想编写一个函数,该函数根据需要满足的某些条件检查异步过程的某些结果。该函数应该使用一些最大的等待时间,循环等待时间,并且应该迭代直到满足条件。
代码和伪代码的混合如下:
fun waitUntilConditionIsMatched() {
val maximumWaitTime = Duration.ofSeconds(10L)
val maximum = currentTimeMillis() + maximumWaitTime.toMillis()
println("Waiting for maximum of $maximumWaitTime for a condition to be matched...")
while (currentTimeMillis() <= maximum) {
if (conditionIsMatched) {
println("...condition matched")
break
} else {
doWait(Duration.ofMillis(500))
}
}
println("...timeout exceeded. Condition was not matched.")
}
有没有一种惯用的方式在Kotlin中编写它?
答案 0 :(得分:0)
您应该研究Kotlin Coroutines,这是该语言的很大一部分,专注于异步编程。
您在Kotlin中的含义的示例应用程序(对于JVM):
import kotlinx.coroutines.*
// dummy condition
var condition = false
fun main(args: Array<String>) {
// this code block is all that's needed to raise condition after half a second
// without blocking current thread
GlobalScope.launch{
delay(500)
println("condition ready")
condition = true
}
// block the current thread while waiting for condition
// this is required to use a suspend function
val result = runBlocking{
println("waiting for result started")
waitForCondition(1000, 100)
}
println("condition was met:" + result)
}
// waits until condition is ready and return true when it is; otherwise returns false
// tailrec function gets rolled out into normal loop under the hood
suspend tailrec fun waitForCondition(maxDelay: Long, checkPeriod: Long) : Boolean{
if(maxDelay < 0) return false
if(condition) return true
delay(checkPeriod)
return waitForCondition(maxDelay - checkPeriod, checkPeriod)
}