代码之家  ›  专栏  ›  技术社区  ›  Sherms

如何:在Kotlin中启动并忘记异步协同路由

  •  8
  • Sherms  · 技术社区  · 9 年前

    我一直在阅读Kotlin的合作例程,但没有找到一个具体问题的答案。

    我不需要请求的返回值,只需要记录异常。

    2 回复  |  直到 9 年前
        1
  •  3
  •   Pau García    6 年前

    请注意,如果已经不存在特定的协程范围(不是挂起函数,即),则可以使用:

    fun Process (item: String): Response {
        GlobalScope.launch {
           ... <YOUR ASYNC (Processing) CODE GOES HERE> ...
        }
        ... <YOUR SYNC CODE GOES HERE> ...
        return Response("Your request for $item is being processed...")
    }
    

    但是,例如,当异步部分引发异常时,请小心可能的内存泄漏。扩展CoroutineScope是一种更好的方法。更多信息请访问 https://discuss.kotlinlang.org/t/unavoidable-memory-leak-when-using-coroutines/11603/7 Why not use GlobalScope.launch?

        2
  •  1
  •   holi-java    9 年前

    大概 kotlinx.coroutines#launch kotlinx.coroutines#async

    launch(CommonPool) {
        for(item in collection){
          val result = apiCall(item);
          log(result);
        }
    }
    

    for(item in collection){
        launch(CommonPool) {
          val result = apiCall(item)
          log(result)
        }
    }