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);
})
}
Comments
-
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 myisLoggedIn()
method into something that can returnObservable<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 about 7 yearsBeware 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 theonAuthStateChanged
(which is a function that removes the listener). Doing so will see the listener removed when the observable is unsubscribed. -
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 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 about 5 yearsbindCallback is the modern approach for the problem since RxJs 6. Checkout these examples.
-
daisura99 over 3 years
bindCallback
is not deprecated rxjs-dev.firebaseapp.com/api/index/function/bindCallback