首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >doAsync Kotlin-android运行不好

doAsync Kotlin-android运行不好
EN

Stack Overflow用户
提问于 2017-11-12 21:33:11
回答 3查看 883关注 0票数 1

当异步结束时,我使用回调函数。但是它的效果不好:

我的案例:

代码语言:javascript
复制
fun function1(callback : (obj1: List<ObjT1>,obj2: List<ObjT1>)-> Unit?){
    doAsync {

        //long task

        uiThread { callback(result1, result2) }
    }
}

回调被调用,但result1result2(列表)为空。我之前检查了列表的内容。

编辑:问题:我的回调是一个接收两个对象result 1和result2的函数,问题是函数回调有时接收的结果是空的,我检查它们的内容,而不是空的。

EN

回答 3

Stack Overflow用户

发布于 2017-11-13 02:59:33

这可能是因为您已将返回类型声明为Unit?,但返回了两个值。一种快速的解决方法是将result1result2放在一个数组中。

票数 0
EN

Stack Overflow用户

发布于 2021-07-19 18:01:43

现在这个问题是关于过时的Kotlin库的。我建议使用协程。

票数 0
EN

Stack Overflow用户

发布于 2017-11-13 01:16:07

考虑使用Kotlin的协程。协程是Kotlin中的一个新特性。从技术上讲,它仍处于实验阶段,但JetBrains告诉我们,它非常稳定。点击此处阅读更多信息:https://kotlinlang.org/docs/reference/coroutines.html

下面是一些示例代码:

代码语言:javascript
复制
fun main(args: Array<String>) = runBlocking { // runBlocking is only needed here because I am calling join below
    val job = launch(UI) { // The launch function allows you to execute suspended functions
        val async1 = doSomethingAsync(250)
        val async2 = doSomethingAsync(50)

        println(async1.await() + async2.await()) // The code within launch will 
        // be paused here until both async1 and async2 have finished
    }

    job.join() // Just wait for the coroutines to finish before stopping the program
}

// Note: this is a suspended function (which means it can be "paused")
suspend fun doSomethingAsync(param1: Long) = async {
    delay(param1) // pause this "thread" (not really a thread)
    println(param1)
    return@async param1 * 2 // return twice the input... just for fun
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47249408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档