Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an Observable from a callback

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;
      });

}
like image 901
Nick Jonas Avatar asked Mar 31 '17 02:03

Nick Jonas


People also ask

What is callback observable?

A callback function is a function passed into another function as an argument which is invoked inside the callee function(here greeting) to complete or after some kind of actions.

How do you make an observable RXJS?

Creating Observableslinkimport { Observable } from 'rxjs'; const observable = new Observable(function subscribe(subscriber) { const id = setInterval(() => { subscriber.next('hi'); }, 1000); });

Is observable create deprecated?

create is deprecated, Instead use new Observable() - Sumit Vekariya - Medium. A custom event service in Angular to subscribe and broadcast messages using observer pattern.

Can you subscribe to an observable?

Executing an Observable But the observable function does not emit any values until it is executed. The subscribe() method calls the observable's function that produces and emits data. Thus, subscribing to an observable starts a flow of data between the observable and the observer.


2 Answers

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

...
return new Observable((subscriber) => {
  firebase
    .auth()
    .onAuthStateChanged((user) => {
      subscriber.next(user);
    })
}
like image 64
am0wa Avatar answered Oct 14 '22 17:10

am0wa


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)
        });
    );
}
like image 34
rohit anand Avatar answered Oct 14 '22 16:10

rohit anand