我想问一个好的开发人员。也许任何人都可以更好地解释。在网络的某个地方,我发现很少有作者使用协程代替例如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))
}
}
这个例子是工作。但我不确定这是好用法。如果回到过去,
GETRESPONSE
在asyncTask中。呼叫与匿名回叫相同。如果使用这种方式是好的,看起来我可以使用这部分没有回调?像这样
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
}