doAsync Kotlin-android无法正常工作
异步结束时,我正在使用回调函数。 但它不能正常工作:(
我的情况:
fun function1(callback : (obj1: List<ObjT1>,obj2: List<ObjT1>)-> Unit?){ doAsync { //long task uiThread { callback(result1, result2) } } }
回调被调用,但result1
和result2
(列表)是空的。 我检查了以前的列表内容。
考虑使用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 }