Pages

Wednesday, January 18, 2017

Using RxJS Observable to return a simple value

So, I have a DataService that is using Observables (kinda the new Promises) to get a bunch of things, then when they are all ready it will get all the values and deal with them.
So functions that use the RxJS .post().map() etc will return Observable fine but I just wanted to return 10. As in the number 10. I don't really care if its Observable per se but I do want to be able to consume the function in the DataService as a promise. So how to you return a number 10? Here goes:

getNumber(): Observable {
   var observable = Observable.create((observer: Observer) => {
      observer.next(10);
      observer.complete();
   });
   return observable;
}

It can then be consumed, along with other promise-style functions and dealt with like promise.all()

Observable.forkJoin([
   this.dataService.getNumber(),
   this.dataService.getSomethingElse()
]).subscribe(results => {
   this.number = results[0];
   this.somethingElse = results[1];
});

Using the subscribe is like using promise.all()

Feels a bit weird at first, but basically if you want to return a promise of a simple type, just create a function like the getNumber() function above.