Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

476
Visualizações
How to run a Firebase Transaction using Kotlin Coroutines?

I'm trying to run a Firebase Transaction under a suspended function in Kotlin and i see no documentation about it.

I'm using

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.5.2'

for coroutines with firebase (eg: setValue(*).await() ) but there seems to be no await function for runTransaction(*)

override suspend fun modifyProductStock(
    product: ProductModel,
    valueToModify: Long,
    replace: Boolean
) {
    CoroutineScope(Dispatchers.Main).launch {
        val restaurantId = authRepository.restaurantId.value ?: throw Exception("No restaurant!")

        val productId = product.id ?: throw Exception("No Product ID!")

        val reference = FirebaseDatabase.getInstance().getReference("database/$restaurantId").child("products")

        if (replace) {
            reference.child(productId).child("stock").setValue(valueToModify).await()
        } else {
            reference.child(productId).child("stock")
                .runTransaction(object : Transaction.Handler {

                    override fun doTransaction(p0: MutableData): Transaction.Result {
                        //any operation
                        return Transaction.success(p0)
                    }

                    override fun onComplete(p0: DatabaseError?, p1: Boolean, p2: DataSnapshot?) {
                    }

                })
        }
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could wrap it in suspendCoroutine:

val result: DataSnapshot? = suspendCoroutine { c ->
    reference.child(productId).child("stock")
        .runTransaction(object : Transaction.Handler {
            override fun doTransaction(p0: MutableData): Transaction.Result {
                //any operation
                return Transaction.success(p0)
            }
    
            override fun onComplete(error: DatabaseError?, p1: Boolean, snapshot: DataSnapshot?) {
                c.resume(snapshot)
            }
        })
}

suspendCoroutine

Obtains the current continuation instance inside suspend functions and suspends the currently running coroutine.
In this function both Continuation.resume and Continuation.resumeWithException can be used either synchronously in the same stack-frame where the suspension function is run or asynchronously later in the same thread or from a different thread of execution.

over 4 years ago · Santiago Trujillo Relatório

0

Given that the Kotlin example in the Firebase documentation on transactions uses the same callback style that you have, it seems indeed that there is no specific support for co-routines there.

It might be worth posting an issue on the Android SDK repo to get it added, or hear why it wasn't added.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda