如何使用 Kotlin 在 Android 中进行异步 Http 调用?
How to make an Asynchronous OkHttp call inAndroid using Kotlin?
我正在尝试使用继承 AsyncTask<Request, Void, Response>
的内部 class 通过 OkHttp 获取 API 数据。现在,当我尝试在 doInBackground(vararg params: Request?): Response
方法中初始化响应时,我被迫像这样初始化 var response : Response? = null
对象,但我无法将其设置为可空类型,如 doInBackground() 方法所期望的那样一个不可为 null 的 Response
。
在 Java 中,初始化 Response
不是强制性的。我该如何避免这种情况?
private class Fake : AsyncTask<Request, Void, Response>() {
val client : OkHttpClient = OkHttpClient()
override fun doInBackground(vararg params: Request?): Response{
// Initialization is compulsory, and cannot be set to Response() as it is not accessible
var response : Response? = null
}
}
正如您提到的,使用 Kotlin,因此在这种情况下,您可以使用与 HTTP 客户端一起工作的改造,并在后台线程中执行使用协程。
它将在后台执行 API 调用并更新 UI 上的数据。
更多参考请学习协程
https://proandroiddev.com/using-retrofit-2-with-kotlin-coroutines-cb112f0fb738
我正在尝试使用继承 AsyncTask<Request, Void, Response>
的内部 class 通过 OkHttp 获取 API 数据。现在,当我尝试在 doInBackground(vararg params: Request?): Response
方法中初始化响应时,我被迫像这样初始化 var response : Response? = null
对象,但我无法将其设置为可空类型,如 doInBackground() 方法所期望的那样一个不可为 null 的 Response
。
在 Java 中,初始化 Response
不是强制性的。我该如何避免这种情况?
private class Fake : AsyncTask<Request, Void, Response>() {
val client : OkHttpClient = OkHttpClient()
override fun doInBackground(vararg params: Request?): Response{
// Initialization is compulsory, and cannot be set to Response() as it is not accessible
var response : Response? = null
}
}
正如您提到的,使用 Kotlin,因此在这种情况下,您可以使用与 HTTP 客户端一起工作的改造,并在后台线程中执行使用协程。
它将在后台执行 API 调用并更新 UI 上的数据。
更多参考请学习协程
https://proandroiddev.com/using-retrofit-2-with-kotlin-coroutines-cb112f0fb738