firebase - 在 Kotlin 中以同步方式运行异步任务

标签 firebase kotlin google-cloud-firestore kotlin-coroutines

我正在尝试运行 Firebase Firestore 的“批处理”作业。由于批处理作业是异步的,并且每个批处理仅处理 500 个文档,因此我创建了一个要以同步方式运行的批处理作业数组,以便我确切知道上一个批处理何时完成,然后继续下一个处理操作。

然而,要在 Kotlin 中执行此操作,当我阅读时,我遇到了一系列术语,例如 runBlocking、Coroutine、Dispatcher、async、await、Context、Suspend、launch、join、Scope、Deferred、Continuation、CommonPool

此外,许多帖子都说在最新版本的 Kotlin 中情况发生了变化。 Kotlin documentation谈论 runBlocking,但是 this post说 runBlocking 是坏事。

经过反复试验,我得到了编译

suspend fun doTheThing() {

   for ( b in batchArray) {
      coroutineScope {
      val job = async { b.commit() }
      job.await()
  }}
}

但是,现在我收到错误提示“暂停函数‘doTheThing’只能从协程或其他暂停函数中调用” 我现在很困惑。我只想按顺序执行这些调用,或者等到所有这些都完成。不确定完成这项工作的正确语法是什么,我弄错了什么概念。


更新:以下代码片段似乎有效:

for ( b in batchArray) {
    runBlocking {b.commit()}
}

这样做是好的做法吗?

最佳答案

协程通常由不同的构建器在某个协程范围的上下文中创建。与构建器一样,挂起函数在协程范围内运行,因此应该在协程范围内调用,协程范围可以通过在协程、挂起函数内调用或从定义的范围内显式调用来提供。

CoroutineScope 是一个接口(interface),它只包含一个属性,即 coroutineContext。 .您可以通过实现 CoroutineScope 接口(interface)并覆盖您自己的协程上下文来简单地创建您自己的范围。

val myCoroutineScope = object : CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = Job() + Dispatchers.Main
}

在您的范围内,您可以使用 launch、async、produce 等构建器。

你可以将你的函数重构为

suspend fun doTheThing() = coroutineScope{
for ( b in batchArray) {
    b.commit()
   }
}

fun main(args: Array<String>) {
    myCoroutineScope.launch {
        doTheThing()
        println("Completed")   
      }
}

我在这里使用了启动,因为我们并不真正关心结果。挂起函数将挂起父协程范围,直到它完成执行。

您还可以选择在另一个调度程序中运行您的作用域

fun main(args: Array<String>) {

myCoroutineScope.launch(Dispatchers.IO) {
    doTheThing()
    println("Completed")
   }
}

为了在我们不希望取消任何子协程来取消范围的情况下获得更好的结果,我们使用 SuperVisor Job 代替常规 Job。

val myCoroutineScope = object : CoroutineScope {
override val coroutineContext: CoroutineContext
    get() = SupervisorJob() + Dispatchers.Default
}

关于firebase - 在 Kotlin 中以同步方式运行异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58469802/

相关文章:

ios - 在 Swift 中从 Firebase 检索数据

flutter - 如何将字段值类型的 serverstamp 添加到我已经存在的 typ <String, Dynamic> 映射

android - 如何随机更改背景?

android - Firestore/Firebase 无法从文件夹获取图像

java - Gradle Kotlin, cucumber 和OKHttp

javascript - 在 FireBase 中使用 Where 查询精确对象

flutter - 无法从 Flutter Firebase 中的 DocumentReference 获取 DownloadURL 或 StorageReference

javascript - Vue,firebase数据库返回空数组

javascript - Firebase 云消息传递 - 调用 firebase.messaging() 时出错

android - 已发送 FCM 消息的状态