简体   繁体   中英

How to return ArrayList from Coroutine?

How to return ArrayList from Coroutine ?

    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)
        }
    }

Error

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? */)

I guess WebApi.ReadingsList is a non-suspending function. That means that you'll need to make a thread wait while it runs. You probably don't want to use Dispatchers.Main for that, since that would run it on the UI thread. Dispatchers.IO would be the normal choice.

You also really shouldn't call suspendCoroutine for this. That's meant for low-level interoperation with other kinds of async callbacks, which you don't have in this case. Something like this would be more appropriate:

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
}

This will run the blocking call in a subordinate job on an IO thread. This ensures that if your coroutine is cancelled, then the subordinate job will be cancelled too -- although that won't interrupt the blocking call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM