I'm a pretty new Firebase user, and I noticed that currentData can be null the first time it is read by the app since it was launched. (Please trust that there is data where I do a transaction.)
But I don't see any way around this problem (other than calling the function that performs the transaction again, which I'd like to avoid), because if I add a condition to know if currentData is null, I have to return either Transaction.success(newCurrentData)
or Transaction.abort()
anyway. In both cases the transaction (doTransaction()
) will not be re-run. I need to know the value at this location the first time, because depending on what is there, different actions will be performed.
So either modify the runTransaction()
so that there is no more empty currentData (which seems - I think - impossible), or do something like myRef.keepSynced(true)
to create the necessary cache before launching the transaction. Unfortunately I don't know these functions very well, and I don't know if they will work. That's why I'm calling on you.
Here is the relevant part of my transaction :
var roomName = ""
database.getReference("rooms").runTransaction(object : Transaction.Handler {
override fun doTransaction(currentData: MutableData): Transaction.Result {
roomName = currentData.children.toList().randomOrNull()?.key //enter to a random existing room
?: database.getReference("rooms").push().key!! // or create one if there is no room
//Do some stuffs depending on roomName, and update the currentData
return Transaction.success(currentData)
}
override fun onComplete(error: DatabaseError?, committed: Boolean, currentData: DataSnapshot?) {
}
}
The currentData is empty the first time (in fact it is not null - since I code in Kotlin -, but does not change the question I ask). If I re-run the transaction without closing my app, there is now a child in the currentData.