【问题标题】:How to get information that coroutine has been destroyed/cancelled?如何获取协程已被销毁/取消的信息?
【发布时间】:2021-05-03 15:55:23
【问题描述】:

我想知道启动的协程何时被销毁。可能吗 ? 协程需要在 Android Application 类范围内的 Repository 类中启动,当应用程序关闭时,我需要进行一些清理。

fun doSomeWorkGlobally() {
   applicationScope.launch { //Application class scope
      val streamListener = object : StreamListener {
          override fun dataSnapshot(val data: Data) {
              dataSharedFlow.tryEmit(data)
          }
      }
      registerToListener.register(streamListener)
      //unregister callback, do clean up work when this coroutine is destroyed (?)
   }
}

如果可以使用 callbackFlow 执行类似 awaitClose 的操作,那就太好了。

附:对于我的情况,callbackFlow 不是 100%,我想知道我是否可以在上面的代码中做类似的事情。

提前致谢!

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    在您的程序中,像这样为您的协程任务分配一个变量。

    fun doSomeWorkGlobally() {
       val job:Job=applicationScope.launch { //Application class scope
          val streamListener = object : StreamListener {
              override fun dataSnapshot(val data: Data) {
                  dataSharedFlow.tryEmit(data)
              }
          }
          registerToListener.register(streamListener)
          //unregister callback, do clean up work when this coroutine is destroyed (?)
       }
    }
    

    那就用这个

    fun Job.runOnCanceled(context: CoroutineContext = DefaultDispatcher, handler: suspend (Job) -> Unit) {
        val job = this
        launch(context) {
            job.join()
            if (job.isCancelled)
                handler(job)
        }
    }
    

    参考:https://discuss.kotlinlang.org/t/coroutine-how-to-get-notification-when-job-is-canceled/6861

    【讨论】:

      【解决方案2】:

      我相信您正在寻找的是Job.invokeOnCompletion,您可以这样使用:

      val job = applicationScope.launch { ... }
      job.invokeOnCompletion {
          // code that runs when the job is done, whether by completing normally,
          // having been cancelled, or due to an error
      }
      

      【讨论】:

      • applicationScope 是在 android Application 类中创建的范围,因此当我关闭应用程序时应该调用 invokeOnCompletion 但它没有
      猜你喜欢
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 2016-06-14
      • 2018-02-13
      相关资源
      最近更新 更多