Firebase child_added without loading all data first

后端 未结 1 1700
萌比男神i
萌比男神i 2021-02-08 22:53

I have an application in which I want to load some amount of initial data (accomplished with Firebase.once(\'value\')) and then at some point later I\'d like to rec

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 23:15

    delete old messages

    If you aren't interested in historical data, then you are utilizing this as a message queue. If that is the case, than old records should be deleted (or archived to an alternate path) after reading them. In this way, the problem is self resolving.

    If you want to maintain this model, a couple good options are available:

    store the last key read and use that as the starting point of your next load

    You could even store the key in Firebase

    var fb = new Firebase(URL);
    fb.child('last_read_key').once('value', function(lastReadSnap) {
       var lastKey = lastReadSnap.val();
       var pri = lastReadSnap.getPriority();
       fb.child('data_to_read').startAt(pri, lastKey).on('child_added', function(snap) {
          if( snap.name() !== lastKey ) {
             console.log('new record', snap.name());
             fb.child('last_read_key').setWithPriority(snap.name(), snap.getPriority());
          }
       });
    });
    

    Use priorities to mark timestamp of old records

    When writing records, use setWithPriority:

    fb.child('records/$recordid').setWithPriority(data, Firebase.ServerValue.TIMESTAMP);
    

    Now you can read records starting at "now":

    fb.child('records').startAt(Date.now()).on('child_added', function(snap) {
        console.log('new child', snap.name());
    });
    

    Note one caveat of using timestamps here. I used Date.now() in the startAt() command, because it doesn't currently support Firebase.ServerValue.TIMESTAMP (bug filed for this).

    0 讨论(0)
提交回复
热议问题