我使用 Retrofit2 通过 kotlin 协程调用 API,但 API 的状态代码为 200、400 和 700。当请求 API 和响应状态代码为 400 或 700 时,“withTimeout”协程可能会异常崩溃。我想使用“withTimeout”协程处理状态代码 400 和 700 响应消息,或者如何自定义“CoroutineScope”,谢谢。
这是我的代码
suspend fun getLogin() {
try {
var result = withTimeout(5_000) { // <----this line can be crashed with http code 700
accountService.getLogin(
LoginRequest() // request data
) // retrofit
}
when (result.state_code) { // api response state code
200 -> {
Timber.i("Create account got data: ${result.source}")
}
400 -> {
//....... handle this status code error
}
700 …Run Code Online (Sandbox Code Playgroud) 我想将相同的“开始时间”合并到列表中的一个(步数、距离和卡路里),我该如何做到这一点。
var listNewStepData = arrayListOf<NewStepData>()
Run Code Online (Sandbox Code Playgroud)
数据类
data class NewStepData (
val startTime: String?,
val endTime: String?,
val step: Int? = 0,
val distance: Int? = 0,
val calorie: Int? = 0
)
Run Code Online (Sandbox Code Playgroud)
这是样本
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-14T00:00:00.000Z, step=4433, distance=0, calorie=0)
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=0, distance=0, calorie=1697)
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-14T00:00:00.000Z, step=0, distance=2436, calorie=0)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=5423, distance=0, calorie=0)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-16T00:00:00.000Z, step=0, distance=0, calorie=1715)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=0, distance=3196, calorie=0)
Run Code Online (Sandbox Code Playgroud)
我想得到这个
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=4433, distance=2436, calorie=1697)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-16T00:00:00.000Z, step=5423, distance=3196, calorie=1715)
Run Code Online (Sandbox Code Playgroud)
谢谢