Angular2 callback vs Promise / Observable

Context:

I have an AWS cognito working on an Angular 2 application. The AWS demo uses callbacks to handle asynchronous requests.

public getSession(callback: CognitoCallback) {
let cognitoUser: CognitoUser = this.getCurrentUser();
let cognitoUtil = this;
cognitoUser.getSession(function (err, session) {
  if (err) {
    let error = new CognitoError(err.name, err.message);
    callback.cognitoCallback(error, null);
    return;
  }
  if (!session.isValid()) {
    let error = new CognitoError("SessionInvalid", "Session is not valid");
    callback.cognitoCallback(error, session);
    return;
  }
  callback.cognitoCallback(null, session);
  cognitoUtil.setCurrentUser(cognitoUser);
  return;
});

      

}

Is it possible to implement the same functionality with a Promise or Observable?

Thanks in advance.

+3


source to share


3 answers


You can also use the theme and create the visible somewhat manually (but at least you can get a better understanding of how to do the transformation).

public getSession(callback: CognitoCallback): Observable<any> {
  let cognitoUser: CognitoUser = this.getCurrentUser();
  let cognitoUtil = this;


  // You can easily get an Observable from an RxJS subject by calling asObservable().
  // more importantly, you can send values/errors to that observable by calling subject.next(valueToSend) or subject.error(errorToSend)
  let subject = new Subject();

  cognitoUser.getSession(function (err, session) {

    if (err) {
      let error = new CognitoError(err.name, err.message);
      //callback.cognitoCallback(error, null);
      // replace with subject error notification
      subject.error(error);
      return;
    }
    if (!session.isValid()) {
      let error = new CognitoError("SessionInvalid", "Session is not valid");
      //callback.cognitoCallback(error, session);
      subject.error(error);
      return;
    }
    //callback.cognitoCallback(null, session);
    // send the session down through the observable
    subject.next(session);
    cognitoUtil.setCurrentUser(cognitoUser);

    // finish off the observable
    subject.complete();
    return;
  });

  return subject.asObservable();
}

      



The above example returns an Observable, which you can then use for other purposes.

+1


source


Quite right. RXJS provides a callback-to-conversion function natively Observable

and uses it exactly as you think.



https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/fromcallback.md

+1


source


If you are using bluebird you can do this

let getSession = Promise.promisify(cognitoUser.getSession);

getSession.then(function (session) {
// session is valid
}, function (err) {
// error getting session
});

      

0


source







All Articles