Skip to content

Instantly share code, notes, and snippets.

@jokamjohn
Forked from puf/WaitForInitialValue.java
Created December 30, 2016 16:23
Show Gist options
  • Save jokamjohn/815c33137199344623f2b28398a76503 to your computer and use it in GitHub Desktop.
Save jokamjohn/815c33137199344623f2b28398a76503 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