HelloWorld
HelloWorld

Reputation: 1863

Transactions and behaviour of snapshotChanges in Firebase realtime database

I am using Firebase and subscribe to snapshotChanges to retrieve an update whenever my realtime database is being updated.

Service A is subscribing to the observer. Service B writes 100 items to the realtime database as follows:

const objs = {'fooA': valueA, 'fooB': valueB, ... };
const dbRef = firebase.database().ref(`projects/${project}`);
return dbRef.transaction((transaction) => {
  return objs;
}, undefined, false);

As you can see objs might contain several hundred items. Once the transaction is executed, I receive an update in Service A for every single item that the other services added to the database.

Since I used a transaction I was hoping that I also only receive 1 single callback, instead of 100's. Currently, I help myself out with a delay timer but I would prefer to avoid that.

this.observer$ = this.db.list(`projects/${project}/`).snapshotChanges()
    .pipe(auditTime(200))
    .subscribe((data) => {
        console.log(data);
    });

Output withauditItem:

(100) [{…}, {…}, {…}, {…}, …]
...

Output without auditItem:

(0) []
(1) [{…}]
> 0:{payload: DataSnapshot, type: 'value'...
(2) [{…}, {…}]
(3) [{…}, {…}, {…}]
(4) [{…}, {…}, {…}, {…}]
...

Any ideas what the API offers for me?

Upvotes: 0

Views: 124

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599766

I'm unable to reproduce the behavior you're describing with the regular JavaScript SDK. Using two app instances in a single jsbin to simulate the two clients:

var primary = firebase.initializeApp(CONFIG);
var secondary = firebase.initializeApp(CONFIG, "secondary");

var ref = primary.database().ref("68615288");
var objs = {};
for (var i=0; i < 100; i++) objs["key_"+i] = "hello";

ref.transaction(function(transaction) {
  return objs;
}, undefined, false);

secondary.database().ref("68615288").on("value", function(snapshot) {
  console.log("Listener got a snapshot with "+snapshot.numChildren()+" child nodes");
});

When I ran this on an empty node, the output I got was:

"Listener got a snapshot with 0 child nodes"

"Listener got a snapshot with 100 child nodes"

This is the expected behavior, as the listener first gets the empty node, and then got the node with 100 children from the transaction.

https://jsbin.com/wuhuyih/1/edit?js,console

Upvotes: 1

Related Questions