Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS, Observable, how to preserve value and switch map to another one

// ticker$ will update every 3s
// showHand$ will only triger after user click button
// I would like to take last ticker price as user order price when user click button

let lastPrice: number;

this.ticker$
  // What I am doing now is preserve value to vairable here.
  .do(ticker => lastPrice = ticker.closePrice)
  .switchMap(() => this.showHand$)
  .subscribe(showHand => {
     // use value here
     this.order.price = lastPrice;
     this.order.amount = showHand.amount;
     this.order.type = showHand.type;

     this.submit();
  });

Any segestion about how to prevser value and switch map together, without one line variable like above?

like image 990
Long Zhao Avatar asked Sep 25 '17 04:09

Long Zhao


People also ask

What RxJS operators can be used to change from one observable to another?

This map() operator is defined in a pipe where you can modify the content of emitted values from one observable to form another new observable. Inside the pipe, you can add your modification logic; in this case, it converts the emitted values to uppercase.

What is the difference between mergeMap and switchMap?

So here's the simple difference — switchMap cancels previous HTTP requests that are still in progress, while mergeMap lets all of them finish. In my case, I needed all requests to go through, as this is a metrics service that's supposed to log all actions that the user performs on the web page, so I used mergeMap .

Does RxJS map return observable?

Summary. We've seen that operators like map and filter are functions which take in and return observables. Each operator exposes a public function like map or filter , which is what we import from 'rxjs/operators' and pass into pipe .


1 Answers

Results selector function is deprecated in version 6 will be removed in version 7.

From docs:

https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#result-selectors

with resultSelector (v5.x)

source.pipe(
 switchMap(fn1, fn2)
)

the same functionality without resultSelector, achieved with inner map

source.pipe(
 switchMap((a, i) => fn1(a, i).pipe(
   map((b, ii) => fn2(a, b, i, ii))
 )
)
like image 96
Cameron Avatar answered Nov 04 '22 19:11

Cameron