好主意或不好主意:使用协程响应 Kotlin



我想问一个好的开发人员。也许任何人都可以更好地解释。在网络上的某个地方,我发现很少有作者使用协程代替,例如异步任务。 只是想提高自己.这是我使用的一小部分代码。 只是想知道 - 它是好还是不。如果没有 - 如何让它变得更好,或者最终我以错误的方式使用它。

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))
}
}

这个例子是 工作 。 但我不确定这是好的用法。 如果回到过去,

获取响应

在 asyncTask 中。呼叫与annonymus回调相同。 如果用这种方式很好,看起来不用回调就可以用这部分了? 就像这样

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.. 
}

如果有人告诉我,会很高兴 - 可以吗:) 问候

我更喜欢使用关键字在调用方的视图中将异步调用视为同步suspend

例如

suspend fun demoCall(): String {
return withContext(Dispatchers.IO) {
Api.getResponse("GET", ApiConstants.test_endpoint) // let's assume it would return string
}
}

来电者可以使用它

CoroutineScope(Dispatchers.Main).launch {
val result = demoCall() //this is async task actually, but it seems like synchronous call here.
//todo something with result
}

最新更新