【发布时间】:2019-04-08 15:26:46
【问题描述】:
我想问一个好的开发者。也许任何人都可以更好地解释。在网络的某个地方,我发现很少有作者使用协程代替例如 asynctasks 。只是想提高自己。这是我使用的一小部分代码。只是想知道-好还是不好。如果没有 - 如何让它变得更好,或者最终我以错误的方式使用它。
fun demoCall(callback: OnResponse) {
CoroutineScope(Dispatchers.Main).launch {
val result = withContext(Dispatchers.IO) {
Api.getResponse("GET", ApiConstants.test_endpoint)//networkOnMainThread exception if i will not use withContext
}
callback?.onResponse(result))
}
}
这个例子是工作。但我不确定它是否很好用。 如果回到过去,
获取响应
在异步任务中。呼叫与匿名回调相同。 如果使用这种方式很好,看起来我可以在没有回调的情况下使用这部分? 就这样
fun demoCall() {
CoroutineScope(Dispatchers.Main).launch {
val result = withContext(Dispatchers.IO) {
Api.getResponse("GET", ApiConstants.test_endpoint)
}
//do anything with result
//populate views , make new response etc..
}
如果有人告诉我,我会很高兴 - 是否可以:) 问候
【问题讨论】:
-
好吧,你绝对不应该为每个请求都创建一个 CoroutineScope,你最好在那个时候使用
GlobalScope。 -
@EpicPandaForce 你能多解释一下吗?请
-
如果你想深入了解 Kotlin Coroutines,我强烈建议你从探索 Coroutine Basics Guide 开始,这是了解何时以及如何使用 Kotlin Coroutines 的第一步
-
@RobertLaFondue 谢谢你的朋友