我有一个使用网络获得companyName.
的异步代码,这个companyName
在另一个方法调用中使用.我不确定Android目前如何正确地等待异步调用完成,然后再继续其他代码.我看到自己在做一份工作
val job = launch {
// async code
companyName = getCompanyName(stock)
}
job.join()
// Do stuff with companyName
但这似乎不再是范例,因为我收到一个错误,不使用CoroutineScope.
,那么在继续其他代码之前,我如何等待协程程序完成运行(而不使用runBlock{})?
以下是我的代码:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.currentStock.observe(viewLifecycleOwner) { stock ->
// TODO: change this to be company name
var companyName = ""
lifecycleScope.launch {
withContext(Dispatchers.IO) {
companyName = getCompanyName(stock)
}
}
deleteTable()
getData(companyName) // RELIES ON COMPANYNAME
}
}
getData(companyName)
的定义为
private suspend fun finraGetCfruid(companyName: String): String {
val url = "https://www.finra.org/finra-data/fixed-income/corp-and-agency"
val queue = Volley.newRequestQueue(requireActivity())
var cfruid = ""
val stringRequest = object: StringRequest(Request.Method.GET, url,
{
},
{ error ->
Log.e("Error", error.toString())
})
{
override fun parseNetworkResponse(response : NetworkResponse) : Response<String> {
val cookies = HttpCookie.parse(response.headers?.get("Set-Cookie"))
val indexOfEqualSign = cookies[0].toString().indexOf('=')
cfruid = cookies[0].toString().substring(indexOfEqualSign + 1)
datainterface.getMoreData(companyName, cfruid)
return super.parseNetworkResponse(response)
}
}
queue.add(stringRequest)
return cfruid
}