gpt4 book ai didi

android - 从挂起函数异常返回对象

转载 作者:行者123 更新时间:2023-11-29 23:05:40 25 4
gpt4 key购买 nike

安卓项目:

fragment :

import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.ResponseBody
import retrofit2.Response
class DefaultTransportService {
companion object {
private val SERVICE_UNAVAILABLE = "{\n" +
" \"code\": -1,\n" + // 503
" \"message\": \"Service unavailable\"\n" +
"}"
private val TAG = DefaultTransportService::class.java.name

suspend fun executeOperation(operation: Deferred<Response<*>>): Any = withContext(Dispatchers.IO) {
try {
operation.await()
} catch (e: Throwable) {
val resultResponse = Response.error<Any>(-1, ResponseBody.create(
MediaType.parse("application/json"),
SERVICE_UNAVAILABLE
))
return resultResponse
}
}
}
}

排队

return resultResponse

编译错误:

'return' is not allowed here

但是当 operation.await() 抛出任何异常时,我需要更改响应。

最佳答案

恕我直言,在您的情况下,我会让您的挂起函数返回一个密封类,类似于:

suspend fun doSomething(): Response =
suspendCancellableCoroutine { cont ->
try {
// make some work here
cont.resume(Response.Success())
} catch (e: Exception) {
val error = "Service unavailable"
cont.resume(Response.Error(error))
Log.e(TAG, e.message)
}
}

sealed class Response {
class Success : Response()
class Error(val message: String?) : Response()
}

关于android - 从挂起函数异常返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56582052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com