How can I access a POST response globally in Kotlin?

0

Issue

I have a kotlin script that gets a token from a server. It then uses that token to perform another request. But, I can’t seem to use the token in the next request because the token has a local scope.

This is my code:

class requests{
    private val client = OkHttpClient()
    private val coroutineScope = CoroutineScope(Dispatchers.Default)

    fun run()  {
        coroutineScope.launch {
            val postBody = "encodedinfo".trimMargin()

            val request = Request.Builder()
                .url("https://example.com")
                .post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN))
                .build()

            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) throw IOException("Unexpected code $response")

                val token = response.body!!.string()
            }
        }
    }

    companion object {
        val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
    }


}

With this code I can’t use the token variable outside of the request code block. This block of code:

client.newCall(request).execute().use { response ->
    if (!response.isSuccessful) throw IOException("Unexpected code $response")

    val token = response.body!!.string()

}

This is the first request that gets the token variable and I need the token so that I can use it in another function so that I can perform the second request and load the users info.

Solution

use is a generic stdlib function used on Closeable. Here is its signature:

inline fun <T : Closeable?, R> T.use(block: (T) -> R): R

As you can see, it returns whatever value the given lambda returns. This result is the last expression in the lambda block, so you can do this to use token outside of the block:

val token = client.newCall(request).execute().use { response ->
    if (!response.isSuccessful) throw IOException("Unexpected code $response")

    response.body!!.string()
}

Answered By – Joffrey

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More