【问题标题】:calling response value inside onCreate (okhttpclient)在 onCreate (okhttpclient) 中调用响应值
【发布时间】:2022-01-02 14:50:38
【问题描述】:

onCreate 代码上方有一个 GET 操作。我想把这个get操作的响应值放到onCreate中。

我的代码

fun run() {
    val request = Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build()

            }
        }
    })
}
}

【问题讨论】:

    标签: android kotlin retrofit okhttp kotlin-coroutines


    【解决方案1】:

    Kotlin coroutines 很简单。使用可以使用suspendCoroutine 与回调一起工作,并使用Activity 中的lifecycleScope 来启动协程。代码将类似于以下内容:

    suspend fun run(): String = suspendCoroutine { continuation ->
        val request = Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build()
    
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                continuation.resumeWithException(e) // resume calling coroutine
                e.printStackTrace()
            }
    
            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")
    
                    for ((name, value) in response.headers) {
                        println("$name: $value")
                    }
    
                    println(response.body!!.string())
                    val qrq = response.body!!.string()
                    continuation.resume(qrq) // resume calling coroutine
                }
            }
        })
    }
    

    并在协程中调用run方法,在onCreate方法中启动:

    override fun onCreate(savedInstanceState: Bundle?) {
    
        setTheme(R.style.AppTheme_MainActivity)
        super.onCreate(savedInstanceState)
        
        lifecycleScope.launch {
            val qrq = run()
            // use qrq, for example to update UI
        }
    
        //another code ......
    
    }
    

    【讨论】:

    • 感谢您的解决方案,但我收到错误 Unresolved reference: launch Using 'lifecycleScope: Scope' is an error. Use ScopeActivity or ScopeFragment instead My Code; override fun onCreate(savedInstanceState: Bundle?) { lifecycleScope.launch { val qrq = run() // use qrq, for example to update UI }
    • 请尝试在app的build.gradle文件中添加依赖androidx.lifecycle:lifecycle-runtime-ktx:2.2.0
    • 还是错误Using 'lifecycleScope: Scope' is an error. Use ScopeActivity or ScopeFragment instead
    • 好的,如果你像lifecycle.coroutineScope.launch { ...这样启动协程,我工作了吗?
    • 这样,代码可以工作,但应用程序突然关闭。 Error: java.net.SocketTimeoutException: timeout lifecycle.coroutineScope.launch { // does not expect this line to run 有如果没有,它会在没有等待的情况下达到底线。
    猜你喜欢
    • 2019-04-29
    • 2017-08-23
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多