我编写了以下(测试)函数来通过 volley 和协程与 google maps api 对话。遗憾的是,当使用 suspendCoroutine 调用它时,它永远不会完成。如果我使用相同的函数,删除协程内容并实现“正常”回调,一切正常。我有点不知所措,这里有什么问题。有人能帮忙吗?
代码执行到 Log.d(LOGTAG, "AFTERAFTER"),但永远不会到达 Log.d("findNaturalLocations", "Response: " + response)
suspend fun testNaturalLocations(tag: Tag, lastKnownUserLocation:
Location): ArrayList<CLDistanceRequest> = suspendCoroutine {
continuation ->
Log.d("findNaturalLocations", "getDistanceAndTimeBetweenLocations")
var distanceRequests = ArrayList<CLDistanceRequest>()
val mapsBaseUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/"
val mapsOutputFormat = "json"
val location = "location=" + lastKnownUserLocation.latitude.toString() + "," + lastKnownUserLocation.longitude.toString()
val radius = "radius=5000"
val keyword = "keyword=Supermarket"
val name = "name=Supermarket"
val sensor = "sensor=true"
val apiKey = "key=API_KEY"
val finishedUrl = mapsBaseUrl + mapsOutputFormat + "?" + location + "&" + radius + "&" + keyword + "&" + name + "&" + sensor + "&" + apiKey
Log.d(LOGTAG, finishedUrl)
val jsObjectRequest = JsonObjectRequest(Request.Method.GET, finishedUrl, null,
Response.Listener<JSONObject> { response ->
Log.d("findNaturalLocations", "Response: " + response)
var results = response.getJSONArray("results")
// parse distanceRequests, ommitted for brevity
continuation.resume(distanceRequests)
},
Response.ErrorListener { error ->
Log.e("Error", error.localizedMessage, error)
continuation.resumeWithException(error)
}
)
Log.d(LOGTAG, "AFTER");
jsObjectRequest.setShouldCache(false)
CLGlobal.getRequestQueue().add(jsObjectRequest)
Log.d(LOGTAG, "AFTERAFTER");
}
用一个简单的回调做同样的事情是完美的。
var i = 0;
runBlocking {
val query = async(CommonPool) {
i = this@CLTaskList.test2()
}
query.await()
}
suspend fun test2():Int = suspendCoroutine<Int> { continuation ->
Log.d("TESTTEST", "TEST2 CALLED")
test {
Log.d("TESTTEST", "CONTINUATION")
continuation.resume(it)
}
}
fun test(completionHandler: (Int) -> Unit) {
Log.d("TESTTEST", "TEST CALLED")
completionHandler(1)
}