rybalkinsd / kohttp

Kotlin DSL http client
https://kohttp.gitbook.io
Apache License 2.0
478 stars 42 forks source link

How can I make this code not so awful? #182

Closed CommanderTvis closed 4 years ago

CommanderTvis commented 4 years ago

I'm pretty new to Kotlin coroutines. How can I improve this horrible code to save asynchronious request and same functional?

package io.github.commandertvis.boredapi

import io.github.rybalkinsd.kohttp.dsl.async.httpGetAsync
import io.github.rybalkinsd.kohttp.ext.url
import java.net.URL
import kotlin.system.exitProcess

suspend fun main() {
    println(httpGetAsync { url(URL("http://www.boredapi.com/api/activity")) }
        .await()
        .use { it.body()!!.string() })

    exitProcess(0)
}
simonenkoi commented 4 years ago

You could use it the next way:

fun main() = runBlocking {
        val response = "http://www.boredapi.com/api/activity".httpGetAsync()
        val string = response.await().use {
            it.body()?.string()
        }
        println(string)
    }

To undestand coroutines better, I strongly recommend jetbrains hands-on: https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/01_Introduction

CommanderTvis commented 4 years ago

my mistake was in launching a coroutine inside runBlocking context :D