Making an Observable from a callback

13,690

Solution 1

You can do it like this.

get isLoggedIn(): Observable<boolean> {

  // want something like this:
  return Observable.create(
    observer => firebase
        .auth()
        .onAuthStateChanged((user) => {
          observer.next(!!user)
        });
    );
}

Solution 2

there is one more way of doing this using bindCallback from rxjs/observable/bindCallback

const observable=bindCallback(functionWhichExpectsCallBack)

e.g

function foo(value, callback) {
  callback(value);
}
//converts callback to observable
    const observable = bindCallback(foo); 
    observable(1)
      .subscribe(console.log); 

Solution 3

Note: bindCallback and Observable.create were deprecated,
you could use new Observable instead:

...
return new Observable((subscriber) => {
  firebase
    .auth()
    .onAuthStateChanged((user) => {
      subscriber.next(user);
    })
}
Share:
13,690
Nick Jonas
Author by

Nick Jonas

Creative Director at Google

Updated on June 15, 2022

Comments

  • Nick Jonas
    Nick Jonas about 2 years

    I have an auth guard that needs an asynchronous response true/false when the site is visited and the user is already logged in.

    I'm using Firebase's onAuthStateChanged (link to docs) and it uses a callback function. How can I turn my isLoggedIn() method into something that can return Observable<boolean>?

    Typscript:

    get isLoggedIn(): Observable<boolean> {
    
        // want something like this:
        return Observable.fromCallback(firebase.auth().onAuthStateChanged).map(user => !!user);
    
        // this returns () => boolean, but I need a promise or observable
        return firebase
          .auth()
          .onAuthStateChanged((user) => {
            return !!user;
          });
    
    }
    
  • cartant
    cartant about 7 years
    Beware that this will add a listener with each property access/subscription and that said listener will not be removed. The arrow function passed to create should return the result of the onAuthStateChanged (which is a function that removes the listener). Doing so will see the listener removed when the observable is unsubscribed.
  • Nick Jonas
    Nick Jonas about 7 years
    @cartant or rohit would you mind add an example of subscribing / unsubscribing to make this answer a bit more thorough?
  • Jaye Renzo Montejo
    Jaye Renzo Montejo over 6 years
    onAuthStateChanged() returns the unsubscribe function so you just need to remove the curly braces in the subscription function when you create the Observable: Observable.create(observer => firebase.auth().onAuthStateChanged(user => observer.next(!!user))).
  • Alex Klaus
    Alex Klaus about 5 years
    bindCallback is the modern approach for the problem since RxJs 6. Checkout these examples.
  • daisura99
    daisura99 over 3 years