我是全新的Kotlin,基本上我是按照一个指南来创建这个应用程序,但是用旧的Kotlin版本完成的。
我的问题是在这里我的java/MainActivity。kt文件
这是我要调用的函数
private suspend fun getTokenAsync(): String {
return getToken()
}
这是来电者
private suspend fun handleLoadWebView() {
//some code here.....
var token: String
runBlocking{
val resp = async { getTokenAsync() }
token = resp.await()
val jsonResp = JSONObject(token)
loadWebView(exampleActivity, jsonResp.getString("access_token"), subdomain, content, options)
}
}
但是在这一行得到错误val resp = async {getTokenAsync()}
你真是把事情搞砸了。
首先,两个函数都是可悬的,所以这里不需要runBlocking()
。事实上,永远不要在挂起函数中使用runBlocking()
。其次,在async()
上运行await()
并没有太大的意义。这与直接调用getTokenAsync()
几乎相同。另外,getTokenAsync()
的名称可能会引起误解,因为挂起函数实际上是同步调用的。
您的整个handleLoadWebView()
可以替换为简单的:
private suspend fun handleLoadWebView() {
val jsonResp = JSONObject(getTokenAsync())
loadWebView(exampleActivity, jsonResp.getString("access_token"), subdomain, content, options)
}
然而,这里可能有更多的事情要做,所以我不能说这是一个完整的工作示例。