最简单的复写挂起函数的回调:
suspend fun suspendFunc() = suspendCoroutine<Int> {
it.resumeWith(Result.success(1))
}
只不过真正的挂起需要真正的切换线程,如果直接调用的话相当于没有挂起。
suspend fun getUserSuspend(name: String) = suspendCoroutine<User> {
continuation ->
githubApi.getUserCallback(name).enqueue(object: Callback<User>{
override fun onFailure(call: Call<User>, t: Throwable) =
continuation.resumeWithException(t)
override fun onResponse(call: Call<User>, response: Response<User>) =
response.takeIf {
it.isSuccessful }?.body()?.let(continuation::resume)
?: continuation.resumeWithException(HttpException(response))
})
}
suspend fun main(){