Skip to content

Instantly share code, notes, and snippets.

@Hasiy
Last active November 16, 2022 03:21
Show Gist options
  • Save Hasiy/e9fccbbc65a4e9f684c0b85c8c933a8c to your computer and use it in GitHub Desktop.
Save Hasiy/e9fccbbc65a4e9f684c0b85c8c933a8c to your computer and use it in GitHub Desktop.
kotlin 协程 http请求挂起处理
suspend fun <T> Call<T>.holdUp(): T {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
LogUtil.w("invokeOnCancellation: cancel the request.")
LogUtil.toastWarning("请求异常,请检查网络后重试!")
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
when (response.isSuccessful) {
true -> {
val body = response.body()
when (body == null) {
true -> {
val invocation = call.request().tag(Invocation::class.java)!!
val method = invocation.method()
val e = KotlinNullPointerException(
"Response from " +
method.declaringClass.name +
'.' +
method.name +
" was null but response body type was declared as non-null"
)
LogUtil.w("KotlinNullPointerException:e$e || response = null ")
LogUtil.toastWarning("服务器异常,请稍候后重试!|| response = null")
continuation.resumeWithException(e)
}
false -> {
when (response.code() != HTTP_SUCCESS) {
true -> {
val invocation = call.request().tag(Invocation::class.java)!!
val method = invocation.method()
val e = KotlinNullPointerException(
"Response from " +
method.declaringClass.name +
'.' +
method.name +
" was null but response body type was declared as non-null"
)
LogUtil.w("KotlinNullPointerException:e$e || code = ${response.code()}")
LogUtil.toastWarning("服务器异常,请稍候后重试! code = ${response.code()}")
continuation.resumeWithException(e)
}
false -> {
continuation.resume(body)
}
}
}
}
}
false -> {
LogUtil.w("response.failure")
LogUtil.toastWarning("请求异常,请稍候后重试!|| response.failure")
continuation.resumeWithException(HttpException(response))
}
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
LogUtil.e("await.enqueue.onFailure::$t")
LogUtil.toastError("请求异常,请稍候后重试!")
continuation.resumeWithException(t)
return
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment