Skip to content

Instantly share code, notes, and snippets.

@puf
Last active March 3, 2018 18:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save puf/146fecdae240ac0e62f858f7650aa85f to your computer and use it in GitHub Desktop.
Save puf/146fecdae240ac0e62f858f7650aa85f to your computer and use it in GitHub Desktop.
Waiting for an initial value

In Firebase you can listen for a single value event, with once()/addListenerForSingleValueEvent()/observeSingleEventOfType(). This adds a temporary listener that will receive a single value event and then unregister it.

But if no value currently exists at the location, this will fire with null. This is valid behavior. But what if you want to wait for the first value at the location?

The files below show how to do that for the three main languages: Java, JavaScript and Swift.

public class Main {
static ValueEventListener mListener;
public static void main(String[] args) throws Exception {
Firebase ref = new Firebase("https://<your-app>.firebaseio.com/");
mListener = ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
System.out.println("The value is now "+snapshot.getValue());
ref.removeEventListener(mListener);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
var ref = new Firebase('https://<your-app>.firebaseio.com');
var listener = ref.on('value', function(snapshot) {
if (snapshot.exists()) {
console.log('Value is now '+snapshot.val());
ref.off('value', listener);
}
});
let ref = Firebase(url: "https://<your-app>.firebaseio.com/")
var handle: FirebaseHandle!
handle = ref.observeEventType(.Value, withBlock: { snapshot in
if snapshot.exists() {
print("The value is now \(snapshot.value)")
ref.removeObserverWithHandle(handle)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment