【问题标题】:doAsync Kotlin-android doesn't work welldoAsync Kotlin-android 不能正常工作
【发布时间】:2017-11-12 13:33:10
【问题描述】:

我在异步结束时使用回调函数。但效果不好:(

我的情况:

fun function1(callback : (obj1: List<ObjT1>,obj2: List<ObjT1>)-> Unit?){
    doAsync {

        //long task

        uiThread { callback(result1, result2) }
    }
}

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

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

【问题讨论】:

  • 我在 Kotlin Android Extensions 中找不到 doasync 或 uiThread,您是否使用了其他库?

标签: android kotlin


【解决方案1】:

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

【讨论】:

  • 不,我的回调是一个接收2个对象result 1和result2的函数,问题是函数回调有时接收到的结果是空的,我检查了它们的内容并且不是空的。
【解决方案2】:

现在这个问题是关于已弃用的 Kotlin 库。 我推荐使用协程。

【讨论】:

    【解决方案3】:

    考虑使用 Kotlin 的协程。协程是 Kotlin 中的一个新功能。它在技术上仍处于试验阶段,但 JetBrains 告诉我们它非常稳定。 在这里阅读更多:https://kotlinlang.org/docs/reference/coroutines.html

    这里是一些示例代码:

    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
    }
    

    【讨论】:

    • 这不能回答问题。
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多