【发布时间】:2023-03-17 01:45:01
【问题描述】:
阅读 Kotlin 文档后,我想出了以下代码(它不起作用 - 见下文)重复函数调用,直到它返回 true 或达到超时。
我想暂停执行,直到此代码块超时或成功 - 它不应该异步执行。
Log.d(TAG, "This is the last line to be logged")
runBlocking {
Log.d(TAG, "this line is never logged")
try {
withTimeout(timeoutMsL) {
while ((isActive) && (!success)) {
success = doSomething()
}
}
}
catch (ex: TimeoutCancellationException) {
Log.d(TAG, "this line is never logged either")
doSomethingElse()
}
}
timeoutMsL 是 Long,典型值为 50 毫秒。
此代码通过 JNI 从 C++ 调用。当我运行它时
- runBlocking 块内没有任何内容运行
- runBlocking 块运行后什么都没有
- 控制权返回给 C++ 调用者
- JNI 中存在异常,但 JNI 不记录 Kotlin 或 Java 异常详细信息。
- adb 中没有记录异常
- 当我尝试使用 try/catch/log 块包围上述代码 sn-p 以捕获 Kotlin 异常时,没有记录任何内容
我已经读到应该避免使用runBlocking,但你也必须从现有的协程中调用withTimeout。
如果我使用正常的协程,调用函数的执行将在达到超时/成功之前继续 - 我需要防止这种情况发生。
在 Kotlin 中应该如何编码?
【问题讨论】:
标签: android kotlin kotlin-coroutines