如何 return 来自协程的 ArrayList?
How to return ArrayList from Coroutine?
如何从 Coroutine
return 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
是一个非挂起函数。这意味着您需要让线程等待 运行s。您可能不想为此使用 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 线程上从属作业中的阻塞调用。这确保如果您的协程被取消,那么从属作业也将被取消——尽管这不会中断阻塞调用。
如何从 Coroutine
return 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
是一个非挂起函数。这意味着您需要让线程等待 运行s。您可能不想为此使用 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 线程上从属作业中的阻塞调用。这确保如果您的协程被取消,那么从属作业也将被取消——尽管这不会中断阻塞调用。