调用onCreate(okhttpclient)内部的响应值



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

我的代码

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

使用Kotlin协程很简单。使用可以使用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 ......
}

最新更新