Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous Kotlin中的异步协同例程_Asynchronous_Kotlin_Coroutine - Fatal编程技术网

Asynchronous Kotlin中的异步协同例程

Asynchronous Kotlin中的异步协同例程,asynchronous,kotlin,coroutine,Asynchronous,Kotlin,Coroutine,我从未在Kotlin中使用async。我不确定我的理解是否正确 我需要方法按钮更改(结果)等待线程完成,以获得结果 fun sendConnection(view: View) { var result = "" if (!connected) { async { val runnable = Runnable() {

我从未在Kotlin中使用async。我不确定我的理解是否正确

我需要方法按钮更改(结果)等待线程完成,以获得结果

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) {

            }
}

您应该使用的模式是
async/await

它将从
async{}
返回一个
Deferred
,您可以使用它来调用
await()
。由于
buttonChange
似乎需要
UI
上下文,因此您可能还需要启动协同程序

launch(UI) {
    try {
        val result = async { me.connect("disconnection") }
        buttonChange(result.await())
    } catch (_: Exception) { }
}

您不应该手动创建线程。

我不理解您的代码。这也类似于Android,在这种情况下,您可能不想等待结果,因为您必须使用ui线程上的回调来处理来自其他线程的结果。顺便说一句,您的
Runnable
没有使用
{}
中的代码。之后,Kotlin中的语法是
val Runnable=Runnable{println(“Hello from Runnable”)}
(或)。
async
也不需要线程+可运行程序,因为它已经使用线程来执行异步代码。