如何使用 Retrofit 进行同步调用
How to make synchronous call using Retrofit
我正在尝试使用 Retrofit call.enqueue ( DrawCircles() ) 获取数据,当我调试时,值在那里,但我认为它不会等待,我的函数继续执行其余行代码。所以问题是我运行它,结果列表(myListCoord)总是空的,如何进行同步调用。
这是我的代码:
doAsync {
var a = DrawCircles()
myListCoord = a.runCircles()
}
fun runCircles(): List<Coordinates>? {
val request = ServiceBuilder.buildService(TmdbEndpoints::class.java)
val call = request.getCorrdinates()
call.enqueue(object : Callback<MyList> {
override fun onResponse(call: Call<MyList>, response: Response<MyList>) {
if (response.isSuccessful){
Toast.makeText(this@DrawCircles, "Succès", Toast.LENGTH_LONG).show()
myListCoord = response.body()!!.locations
}
}
override fun onFailure(call: Call<MyList>, t: Throwable) {
Toast.makeText(this@DrawCircles, "${t.message}", Toast.LENGTH_SHORT).show()
}
})
return myListCoord
}
您是否尝试过使用 call.execute()
而不是 call.enqueue()
?
来自docs:
void enqueue(Callback<T> callback)
Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response.
Response<T> execute() throws IOException
Synchronously send the request and return its response.
(强调我的)
我正在尝试使用 Retrofit call.enqueue ( DrawCircles() ) 获取数据,当我调试时,值在那里,但我认为它不会等待,我的函数继续执行其余行代码。所以问题是我运行它,结果列表(myListCoord)总是空的,如何进行同步调用。
这是我的代码:
doAsync {
var a = DrawCircles()
myListCoord = a.runCircles()
}
fun runCircles(): List<Coordinates>? {
val request = ServiceBuilder.buildService(TmdbEndpoints::class.java)
val call = request.getCorrdinates()
call.enqueue(object : Callback<MyList> {
override fun onResponse(call: Call<MyList>, response: Response<MyList>) {
if (response.isSuccessful){
Toast.makeText(this@DrawCircles, "Succès", Toast.LENGTH_LONG).show()
myListCoord = response.body()!!.locations
}
}
override fun onFailure(call: Call<MyList>, t: Throwable) {
Toast.makeText(this@DrawCircles, "${t.message}", Toast.LENGTH_SHORT).show()
}
})
return myListCoord
}
您是否尝试过使用 call.execute()
而不是 call.enqueue()
?
来自docs:
void enqueue(Callback<T> callback)
Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response.
Response<T> execute() throws IOException
Synchronously send the request and return its response.
(强调我的)