0

I want to utilize the pipe command and link from one observable, process the output data in the subscription, then run a function to transform the data and then input the result to a new observable function. I was trying to link the function with the pipe and switchMap but I am not sure how to elevate and be able to plug the transform function between the 2 observables

service.FirstFunction().pipe( 
     switchMap((info) => this.Transform(info),switchMap((data) => service.secondFunction(data))
 )
.subscription((x)=> this.Updatedata(x));

this.transform is a regular function and not an observable

thanks

Wally

Giannis
  • 1,790
  • 1
  • 11
  • 29
Wally
  • 43
  • 4

2 Answers2

1

You're close. You don't need the first switchMap to transform the data. It could done inside a single switchMap.

service.FirstFunction().pipe(
  switchMap(info => service.secondFunction(this.Transform(info)))
).subscription(
  (x) => this.Updatedata(x)
);
ruth
  • 29,535
  • 4
  • 30
  • 57
  • thank you , I will test it right now, why sometimes the this is undefined? – Wally Nov 12 '20 at 14:19
  • You need to either bind it using `bind(this)` or use arrow function like here. You could learn more about it [here](https://stackoverflow.com/q/20279484/6513921). – ruth Nov 12 '20 at 14:24
1

Looks like this.Transform does not return an observable, so switchMap is not needed here. You can just use map instead:

service.FirstFunction().pipe( 
  map((info) => this.Transform(info),
  switchMap((data) => service.secondFunction(data))
).subscribe((x)=> this.Updatedata(x));

Also, you can simplify the code by passing in function:

service.FirstFunction().pipe( 
  map(this.Transform.bind(this)),
  switchMap(service.secondFunction.bind(service))
).subscribe(this.Updatedata.bind(this));

You have to bind because the funtions are bind to an object. If there is no this used in the functions you can just skip bind work.

And BTW, to simplify the subscribe work you can also use tap here:

service.FirstFunction().pipe( 
  map(this.Transform.bind(this)),
  switchMap(service.secondFunction.bind(service)),
  tap(this.Updatedata.bind(this))
).subscribe();