gpt4 book ai didi

android - 如何从协程返回 ArrayList?

转载 作者:行者123 更新时间:2023-11-29 16:28:51 25 4
gpt4 key购买 nike

如何从Coroutine返回ArrayList

    GlobalScope.launch {
val list = retrieveData(firstDateOfMonth,lastDateOfMonth)
}

suspend fun retrieveData(
first: Date,
last: Date,
): ArrayList<Readings> = suspendCoroutine { c ->

var sensorReadingsList : ArrayList<Readings>?=null

GlobalScope.launch(Dispatchers.Main) {
val task2 = async {
WebApi.ReadingsList(
activity,auth_token, first, last
)
}
val resp2 = task2.await()

if (resp2?.status == "Success") {
sensorReadingsList = resp2?.organization_sensor_readings
}

c.resume(sensorReadingsList)
}
}

错误

Type inference failed: Cannot infer type parameter T in inline fun Continuation.resume(value: T): Unit None of the following substitutions receiver: Continuation? /* = java.util.ArrayList? */> arguments: (kotlin.collections.ArrayList? /* = java.util.ArrayList? */)

最佳答案

我想 WebApi.ReadingsList 是一个非挂起函数。这意味着您需要让线程在运行时等待。您可能不想为此使用 Dispatchers.Main,因为那样会在 UI 线程上运行它。 Dispatchers.IO 将是正常的选择。

您也不应该为此调用 suspendCoroutine。这意味着与其他类型的异步回调的低级互操作,在这种情况下您没有。这样的事情会更合适:

suspend fun retrieveData(
first: Date,
last: Date,
): ArrayList<Readings>? {
val resp2 = withContext(Dispatchers.IO) {
WebApi.ReadingsList(activity,auth_token, first, last)
}
if (resp2?.status == "Success") {
return resp2?.organization_sensor_readings
}
return null
}

这将在 IO 线程的从属作业中运行阻塞调用。这确保如果您的协程被取消,那么从属作业也将被取消——尽管这不会中断阻塞调用。

关于android - 如何从协程返回 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212100/

25 4 0