Synthiatic
Synthiatic

Reputation: 261

How to Asynchrounsly call HTTP Post API?

I have an issue with my android app. I'm fairly new with it and have some issues with finding the correct documentation for a asynchronous. I'm using the kohttp library to help me a bit.

The thing is, you can't run this on the main UI thread so I want to make this request Async. I can't find a clear reference in the documentation and I don't really know how to do this in plain Kotlin.

This is what I come up with; in a separate class named LoginCall. I tried other answers, this however didn't result in success. How can I run this on a new thread and still use the response?

    class LoginCall {
    fun callLoginRequest(a:String, b:String): Any {

        val response: Response = httpPost {
            host = "XXX"
            path = "XXX"

            param { }
            header { }

            body {
                form {
                    "email" to a
                    "password" to b
                }
            }
        }

        return response
    }
}

Upvotes: 4

Views: 1515

Answers (3)

Evgeny Vorobyov
Evgeny Vorobyov

Reputation: 41

Since kohttp 0.10.0 you can use async methods for such cases. You can try them.

Code example:

suspend fun callLoginRequest(a:String, b:String): Any {

    val response: Differed<Response> = httpPostAsync {
        host = "XXX"
        path = "XXX"

        param { }
        header { }

        body {
            form {
                "email" to a
                "password" to b
            }
        }
    }

    // for further usage in coroutines
    return response.await() 
}

And call this function from coroutine

Upvotes: 1

Sergei Rybalkin
Sergei Rybalkin

Reputation: 3453

Also, you can create an issue to implement asyncHttpPost.

Upvotes: 1

MadScientist
MadScientist

Reputation: 2164

There are many ways to achieve this, if you're using android as the underlying platform, you can use the native component called AsyncTask a good SO post on how to use it.

If you wish to leverage kotlin as a language and the features provided by it, you can try using coroutines ref.

Personally, i would recommend coroutines, it simplifies exception and error handling, also prevents callback hell.

here's a sample of the same code in a coroutine,

// global 
private val mainScope = CoroutineScope(Dispatchers.MAIN + SupervisorJob())

// inside a method 
mainScope.launch{
  withContext(Dispatchers.IO){
    // do your async task here, as you can see, you're doing this in an IO thread scope. 
  }
}

Upvotes: 2

Related Questions