Ruan
Ruan

Reputation: 4283

Return observable from firebase onchange

How on earth do you return an observable of (ex type User) from an on-change function in firebase. Normally you can just do a .then but this funcition is inside the .on so I have No clue how to get an observable out of there.

Note: I can just set of(that.user); to my observable inside there, but then my observable will be null as my app starts. So ideally you'll set your observable equal to the below methods return

 this.fire.database().ref('users/' + firebaseUser.uid)
       .on('value', function (snapshot) {
          if (snapshot.val()) {
            that.user = snapshot.val();
            return of(that.user);
          }
        });

Upvotes: 0

Views: 327

Answers (1)

AvidRP
AvidRP

Reputation: 383

You can't just return a value for the method like Doug Stevenson said. What you actually want to do is use callbacks. For example:

public interface ResultsListener{

  public void onResult(User user);
  public void onFailed();

}


public void makeFirebaseCall(ResultsListener listener) {
    this.fire.database().ref('users/' + firebaseUser.uid)
           .on('value', function (snapshot) {
              if (snapshot.val()) {
                that.user = snapshot.val();
                listener.onResult(that.user);
              }
            });
}

And when you make the call to makeFirebaseCall() you can just do the following:

makeFirebaseCall(new ResultsListener() {
    @override
    void onResult(User user) {
        // do something with user
    }

    @override
    void onFailed() {
        // something failed
    }

});

Hopefully this helps!

Upvotes: 1

Related Questions