0

using Rxjs I need to do 4 actions in an Angular service and then the component consumes that service function:

-call the function "ensureHasCache():Observable"

-call the function "create():Observable"

-take the result of create() and assign a local variable (this._companies.push (newEntity);)

-then return an Observable in order to consume it on the UI

This is my service code where the 4 actions take place:

public create (data:Company):Observable<Company>
{       
    return this.ensureHasCache ().switchMap (res => {
        return super.create (data);
    }).switchMap ((newEntity:Company) => {            
        this._companies.push (newEntity);
        return ObservableUtils.fromResult (newEntity);
    });
}       

As you can see in the last switchMap I need to return an observable but actually I already have the result. So I have to call "fromResult". But in this way I need to create a new observalbe ("fromResult" creates a new Observable) even if I actually dont need it.

Is there a more elegat way?

This is the code of fromResult:

public static fromResult<T> (result:T):Observable<T>
{
    return new Observable<T> (obs => {
        obs.next (result);
        obs.complete ();
    });
}
user3471528
  • 3,013
  • 6
  • 36
  • 60

1 Answers1

1

I would do something like that using the do operator of observables:

public create (data:Company):Observable<Company> {       
  return this.ensureHasCache ().switchMap (res => {
    return super.create (data);
  }).do((newEntity:Company) => {            
    this._companies.push (newEntity);
  });
} 
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360