Quessts
Quessts

Reputation: 440

How can I access a POST response globally in Kotlin?

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.

Upvotes: 1

Views: 163

Answers (1)

Joffrey
Joffrey

Reputation: 37730

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()
}

Upvotes: 2

Related Questions