简体   繁体   English

好主意还是不好:用协程反应Kotlin

[英]good idea or not good : to use coroutines for response Kotlin

i want to ask a good developers. 我想问一个好的开发商。 Maybe anyone can better explaine. 也许任何人都可以更好地解释。 Somewhere in web i found that few authors used coroutines instead for example asynctasks . 在网络的某个地方,我发现很少有作者使用协程代替例如asynctasks。 Just trying to improve myself . 只是想提高自己。 Here a small part of code which i used . 这是我使用的一小部分代码。 Just want to know - it's good or no. 只想知道-是好是坏。 If no - how to make it's better or maybe in final im using this in wrong way. 如果没有-如何使其变得更好,或者最终以错误的方式使用此方法。

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

This example is work . 这个例子是工作。 But im not sure it's good usage. 但是我不确定它的用法是否正确。 If back to past , 如果回到过去,

getResponse GETRESPONSE

was in asyncTask. 在asyncTask中。 Call was same with annonymus callback. 呼叫与匿名回叫相同。 If to use this way is good , looks like i can use this part without callback ? 如果使用这种方式很好,看来我可以使用该部分而无需回调? Just like this 像这样

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

will be very happy if any tell me - is it ok or no :) Regards 如果有什么话告诉我,我会很高兴-可以吗?:)

I prefer making asynchronous calls be seen like synchronous in caller's view using suspend keyword. 我更喜欢使用suspend关键字在调用者的视图中将异步调用视为同步。

For example, 例如,

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

and caller can use it 呼叫者可以使用它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM