【问题标题】:good idea or not good : to use coroutines for response Kotlin好主意或坏主意:使用协程响应 Kotlin
【发布时间】: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 谢谢你的朋友

标签: android kotlin coroutine


【解决方案1】:

我更喜欢使用 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2011-09-26
    相关资源
    最近更新 更多