Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 callback vs Promise/Observable

Context:

I have AWS cognito working on an Angular 2 app. 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 Promise or Observable?

Thanks in advance.

like image 357
Kelvin Yang Avatar asked Jul 09 '26 09:07

Kelvin Yang


1 Answers

You can also make use of a Subject and create the observable somewhat manually (but at least you might better understand how to do the conversion).

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 example above will return an Observable that you can then use for other purposes.

like image 136
snorkpete Avatar answered Jul 11 '26 23:07

snorkpete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!