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

这一生的挚爱 提交于 2020-06-11 01:22:11

问题


// 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?


回答1:


I think this is the operator

this.showHand$.take(1)
  .withLatestFrom(this.ticker$)
  .subscribe(([showHand, ticker]) => {
    this.order.price = ticker.closePrice;
    this.order.amount = showHand.amount;
    this.order.type = showHand.type;
    this.submit();      
  });

Note, take(1) will close subscription, but if you want the user to be able to press the button many times, save the subscription to a const and unsubscribe when finished.




回答2:


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))
 )
)



回答3:


The behaviour you require is already possible with an overload of SwitchMap with a selectorFunc for the combination of every (outerValue,innerValue):

this.ticker$
  .switchMap(
    () => this.showHand$,
    (tickerValue, switchMap) => tickerValue
  )
  .subscribe(showHand => { });


来源:https://stackoverflow.com/questions/46397864/rxjs-observable-how-to-preserve-value-and-switch-map-to-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!