To increment the quantity in the Realtime Database, I can simply use:
override fun incrementQuantity() = flow {
try {
heroIdRef.update("quantity", FieldValue.increment(1)).await()
emit(Result.Success(true))
} catch (e: Exception) {
emit(Result.Failure(e))
}
}
And works well. The problem comes when I need to check the quantity
first and then increment. The above solution doesn't help, so I need to use transactions. Here is what I've tried:
override fun incrementQuantity() {
val transaction = object : Transaction.Handler {
override fun doTransaction(mutableData: MutableData): Transaction.Result {
val quantity = mutableData.getValue(Long::class.java) ?: return Transaction.success(mutableData)
if (quantity == 1L) {
mutableData.value = null
} else {
mutableData.value = quantity + 1
}
return Transaction.success(mutableData)
}
override fun onComplete(error: DatabaseError?, committed: Boolean, data: DataSnapshot?) {
throw error.toException()
}
}
heroIdRef.runTransaction(transaction)
}
And works, but I cannot see how use Kotlin Coroutines. I just want to call await() and return a flow, as in the first example. How can I do that?