Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CoolWeatherNetwork 的疑问 #25

Closed
Likeyong opened this issue Dec 5, 2019 · 1 comment
Closed

CoolWeatherNetwork 的疑问 #25

Likeyong opened this issue Dec 5, 2019 · 1 comment

Comments

@Likeyong
Copy link

Likeyong commented Dec 5, 2019

`
private suspend fun Call.await(): T {
return suspendCoroutine { continuation ->

        enqueue(object : Callback<T> {
            override fun onFailure(call: Call<T>, t: Throwable) {
                continuation.resumeWithException(t)
            }

            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body = response.body()
                if (body != null) continuation.resume(body)
                else continuation.resumeWithException(RuntimeException("response body is null"))
            }
        })


        /* val execute = execute()
        if (execute.isSuccessful){
            val body = execute.body()
            body?.let { continuation.resume(body) }
        }else{
            continuation.resumeWithException(Throwable(execute.message()))
        }*/

    }
}

`
郭神,想请教一下这里为啥使用异步请求. 因为这里是在IO线程执行的. 我尝试了一下把这里改成同步执行也可以. 改成同步执行,唯一的不足之处就是:无法准确的获取onFailure的信息. 所以想请教一下是处于啥方面考虑然后使用异步执行的,

@guolindev
Copy link
Owner

我忘记suspendCoroutine是会返回到哪个线程中了,如果是会返回到外层协程所属的线程,那么应该没什么问题,因为外面的协程也是运行在IO线程当中的。但是这里无论如何enqueue一下是个比较好的习惯,因为你不需要依赖于外层线程是什么情况,总是可以保证程序是正确的。不然的话一旦外层线程是主线程,那么你在主线程里执行网络请求就要报错了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants