Christopher Christopher - 1 month ago 20
TypeScript Question

Observable Shorthand

I'm wondering if there is a better way (read: shorter) to write the following function in Typescript/Angular2. I find myself in a situation a lot of times where I'm caching observable server data and returning the cached value if it exists. My way (below) seems to be a bit overkill.

getUser(){
return Observable.create(s => {
if(!this.user)
this.connection.identity((err, res) => {
this.user = res;
s.next(res);
s.complete();
})
else{
s.next(this.user);
s.complete();
}
});
}

Answer

This is a little shorter and it handles errors:

import "rxjs/add/observable/of";
import "rxjs/add/observable/bindNodeCallback";
import { Observable } from "rxjs/Observable";
...
getUser() {
  return this.user ?
    Observable.of(this.user) :
    Observable.bindNodeCallback(
      this.connection.identity.bind(this.connection),
      res => this.user = res
    )();
}
Comments