Making an Observable from a callback

坚强是说给别人听的谎言 提交于 2019-12-23 08:47:36

问题


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

}

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



回答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); 


来源:https://stackoverflow.com/questions/43131162/making-an-observable-from-a-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!