Home > Net >  How do get operations on firebase transactions instantly return the result
How do get operations on firebase transactions instantly return the result

Time:11-28

I've been playing with Firebase transactions with Android for some time and that thought crossed my mind. When you run a transaction like this one the variable data gets assigned instantly using a synchronous call to transaction.get():

val db = Firebase.firestore
db.runTransaction { transaction ->
    val ref = db.collection("example").document("exampledoc")
    val ref2 = db.collection("example").document("exampledoc2")

    val data = transaction.get(ref)
    val data2 = transaction.get(ref2)
}

How can it get the value instantly? Does it request a copy of the entire database or of a portion of it before running the transaction and then instantly returns the values when they are requested while running it? If it requests a copy of a portion of the database, how does it know what portion to get before the requests are even made?

I looked for this everywhere and couldn't find anyone explaining how it works.

CodePudding user response:

It's not really instant, but it is synchronous, and nothing is preloaded. Each call to get() inside a transaction requests that specific document to be fetched and returned on demand so you can work with its contents inside the transaction handler. If you have a slow network connection, you will more clearly observe the delay. Try adding some timing code - you will see that it is not single-digit milliseconds that you would observe from something that is truly instant from being in memory.

While you might expect the method to return a Task like other methods that read and write the database, that is just not the case in a transaction. The API assumes that you need the data immediately and hides the implementation detail of doing the request so that you don't have to worry about dealing with so many tasks.

You might be helped further by reading the source code.

  • Related