Search code examples
angularrxjsionic2

How to just return a defined variable from an observable synchronously


So I inherited and angular/ionic app that I am trying to do some testing on, the app is having a bunch of issues, I am currently in the process of changing the functions that store/return the data it uses. The app is set up to consume this data through observables which I am not familiar with at all. All the functions in the app are doing a .subscribe() where the original functions are performing some async function. I want to modify these functions to just return a global variable synchronously, I tried this but this does not seem to be working. Can anyone help me out here?

public getDataObject(): Observable<DataObject> {
  return Observable.create((do: Data Object) => {
    if (this.globalDataObject === null) {
      throw new Error("Test Error, global var is null")
    }
    let alert = this.alrtCntrl.create({
      title: "INFO",
      subTitle: `Returning Global Data Object Variable`,
      buttons: ["OK"],
    })
    alert.present();
    return this.globalDataObject;
  })
}

Solution

  • Replacing the Observable.create wrapper with the of() operator should give you the behavior you're looking for.

    public getDataObject(): Observable<DataObject> {
      if (this.globalDataObject === null) {
        throw new Error("Test Error, global var is null")
      }
      const alert = this.alrtCntrl.create({
        title: "INFO",
        subTitle: `Returning Global Data Object Variable`,
        buttons: ["OK"],
      })
      alert.present();
      return of(this.globalDataObject);
    }
    

    The of() operator will emit whatever synchronous value you put inside.