从Kotlin和okhttp中的函数检索变量结果

问题描述 投票:0回答:1

我是Kotlin的新手,非常感谢您的帮助。我可以在getVariable()函数中获取jsonStringArray变量的值,但是我不确定如何在kotlin中检索该函数之外的值。

//Need help on the below variable outside getVariable function 
val output=jsonStringArray.getVariable()???     
//Working Code
private fun getVariable() {
val itemDetailURL="https://www.google.com"
val client= OkHttpClient()
val request= Request.Builder().url(itemDetailURL).build()
client.newCall(request).enqueue(object: Callback
{
    override fun onResponse(call: Call?, response: Response?) {
        val jsonStringArray=response?.body()?.string()
        println("JSON Output: $jsonStringArray")

    }
    override fun onFailure(call: Call, e: IOException) {
    }
}
)
}
android kotlin retrofit okhttp okhttp3
1个回答
0
投票
我正在执行异步调用,因为我在主线程中(并且同步调用是一个错误)。我想访问返回的消息响应的主体。由于返回是异步处理的,因此“返回”主线程上的应用程序值的方式似乎是在设置类属性,用赋值替换下面的println-Kotlin不允许这样做。主线程如何访问http请求的结果?似乎需要将结果“传递”回去作为副作用,但是....有关此问题的推理,请参阅我的评论

class MyCallback() : Callback { var resultFromCall = "" override fun onFailure(call: Call, e: IOException) {} override fun onResponse(call: Call, response: Response) = // assign to property "resultFromCall" to be read by main thread? But called asynchronously //update Android UI? spawning other events. But class doesn't know abobut the UI component "passageShown" and can't pass View in because this is an overide... passageShown.setText(response.body.toString()); //println("Results of call to URL:" + response.body.toString()) }

返回响应,并仅显示一条打印语句-但我似乎无法获得对监视Android应用程序UI的主线程的响应的值。我欢迎您的想法。

© www.soinside.com 2019 - 2024. All rights reserved.