我的Android应用程序有问题。我对它比较陌生,并且在查找异步的正确文档时遇到一些问题。我正在使用kohttp库对我有所帮助。
问题是,您不能在主UI线程上运行此命令,因此我想使此请求异步。我在文档中找不到清晰的参考资料,而且我真的不知道如何在普通Kotlin中做到这一点。
这是我想出的;在名为LoginCall
的单独类中。我尝试了其他答案,但这并没有成功。我该如何在新线程上运行它并仍然使用响应?
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
}
}
答案 0 :(得分:1)
有很多方法可以实现这一目标,如果您使用android作为基础平台,则可以使用名为AsyncTask
的本机组件post来了解如何使用它。
如果您希望利用kotlin作为语言及其提供的功能,可以尝试使用coroutines
ref。
我个人会推荐coroutines
,它可以简化异常和错误处理,还可以防止回调地狱。
这是协程中相同代码的示例,
// 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.
}
}
答案 1 :(得分:1)
自kohttp 0.10.0起,您可以在这种情况下使用异步方法。您可以尝试一下。
代码示例:
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()
}
然后从协程调用此函数
答案 2 :(得分:0)
此外,您可以create个问题来实施asyncHttpPost
。