【发布时间】:2018-10-12 10:10:07
【问题描述】:
我从不在 Kotlin 中使用异步。我不确定我的理解是否正确。
我需要buttonChange(result)方法等待线程结束,才能得到结果。
fun sendConnection(view: View) {
var result = ""
if (!connected) {
async {
val runnable = Runnable()
{
result = me.connect("connection")
}
val threadSend = Thread(runnable)
threadSend.start()
}
buttonChange(result)
}
catch (e: Exception) {}
} else {
try {
async {
val runnable = Runnable()
{
result = me.connect("disconnection")
}
val threadSend = Thread(runnable)
threadSend.start()
}
buttonChange(result)
} catch (e: Exception) {
}
}
【问题讨论】:
-
我不明白你的代码。这也看起来像 Android,在这种情况下,您可能不想等待结果,因为您必须在 ui 线程上使用回调来处理来自其他线程的结果。顺便说一句,您的
Runnable之后不再使用{}中的代码,Kotlin 中的语法是val runnable = Runnable{ println("Hello from runnable") }(或object : Runnable() {}syntax)。async也不需要线程 + 可运行文件,因为它已经使用线程来执行异步代码。
标签: asynchronous kotlin coroutine