【问题标题】:Async Co-Routine in KotlinKotlin 中的异步协同程序
【发布时间】: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


【解决方案1】:

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

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

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

您不应该手动创建线程。

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 2019-01-15
    • 2022-01-18
    • 1970-01-01
    • 2022-01-13
    • 2018-02-22
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多