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

循环计时的Kotlin

  •  0
  • Jared  · 技术社区  · 6 年前

    所以我尝试将两个玩家配对到一个游戏中,并在为for-loop的执行时间而挣扎。我使用firebase firestore作为我的后端,顺便说一句,我希望每次for循环迭代都要等到最后一次完成,因为循环中的每个事务都需要一两秒钟,我只想加入一个游戏。现在它基本上加入了所有的空游戏,因为for循环并不等待最后一个循环完成。我认为这是一个异步/同步问题。

    下面是我的for循环代码:

    for (document: DocumentSnapshot in task.result) {
                                firestoreInstance.runTransaction(Transaction.Function<Void> { transaction ->
                                    val snapshot = transaction.get(document.reference)
                                    transaction.update(document.reference, "joiner", FirebaseAuth.getInstance().uid)
    
                                    // Success
                                    null
                                }).addOnSuccessListener {
                                    Log.d(TAG, "Transaction success!")
                                    onComplete(document.reference)
                                    gameJoined = true
                                }.addOnFailureListener { e ->
                                    Log.w(TAG, "Transaction failure.", e)
                                    onComplete(null)
                                }
                            }
    

    1 回复  |  直到 6 年前
        1
  •  3
  •   TheWanderer    6 年前

    使用递归:

    fun myLoopOrWhatever(result: List<DocumentSnapshot>, index: Int) {
        val doc = result[index]
    
        firestoreInstance.runTransaction(Transaction.Function<Void> { transaction -> 
            val snapshot = transaction.get(doc.reference)
            transation.update(doc.reference, "joiner", FirebaseAuth.getInstance().uid)
            null
        }).addOnSuccessListener {
            //your logic
            if (index < result.size) myLoopOrWhatever(result, index++)
        }.addOnFailureListener { e -> 
            //your logic
            if (index < result.size) myLoopOrWhatever(result, index++)
        }
    }
    

    从路过开始 task.result 0

    我只是在猜 任务.结果