如何在不使用GlobalsCope.launch {}的Kotlin中调用异步/等待方法
我正在尝试使用kotlin的异步/等待API呼叫。我已经创建了该方法,并且可以工作!但是现在我不知道如何在不使用GlobalScope.launch {}的情况下在活动或视图模型中调用它?还有另一种方式吗?
class Service{
var client: OkHttpClient = OkHttpClient();
fun getRequest(sUrl: String) =GlobalScope.async {
Thread.sleep(2000)
var result: String? = null
try {
// Create URL
val url = URL(sUrl)
// Build request
val request = Request.Builder().url(url).build()
// Execute request
val response = client.newCall(request).execute()
result = response.body?.string()
}
catch(err:Error) {
print("Error when executing get request: "+err.localizedMessage)
}
return@async result
}
}
I am trying to use async/await in kotlin to make calls to an api. I already created the method and it works! but now I don't know how to call it in an activity or in a viewmodel WITHOUT using GlobalScope.launch {} ?? There is another way ?
class Service{
var client: OkHttpClient = OkHttpClient();
fun getRequest(sUrl: String) =GlobalScope.async {
Thread.sleep(2000)
var result: String? = null
try {
// Create URL
val url = URL(sUrl)
// Build request
val request = Request.Builder().url(url).build()
// Execute request
val response = client.newCall(request).execute()
result = response.body?.string()
}
catch(err:Error) {
print("Error when executing get request: "+err.localizedMessage)
}
return@async result
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论