当异步结束时,我使用回调函数。但是它的效果不好:
我的案例:
fun function1(callback : (obj1: List<ObjT1>,obj2: List<ObjT1>)-> Unit?){
doAsync {
//long task
uiThread { callback(result1, result2) }
}
}回调被调用,但result1和result2(列表)为空。我之前检查了列表的内容。
编辑:问题:我的回调是一个接收两个对象result 1和result2的函数,问题是函数回调有时接收的结果是空的,我检查它们的内容,而不是空的。
发布于 2017-11-13 02:59:33
这可能是因为您已将返回类型声明为Unit?,但返回了两个值。一种快速的解决方法是将result1和result2放在一个数组中。
发布于 2021-07-19 18:01:43
现在这个问题是关于过时的Kotlin库的。我建议使用协程。
发布于 2017-11-13 01:16:07
考虑使用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
}https://stackoverflow.com/questions/47249408
复制相似问题