簡體   English   中英

RxJS,Observable,如何保存值並將映射切換到另一個

[英]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();
  });

關於如何將 prevser value 和 switch map 放在一起的任何部分,沒有像上面那樣的一行變量?

結果選擇器功能在第 6 版中已棄用,將在第 7 版中刪除。

從文檔:

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

使用 resultSelector (v5.x)

source.pipe(
 switchMap(fn1, fn2)
)

沒有 resultSelector 的相同功能,通過內部地圖實現

source.pipe(
 switchMap((a, i) => fn1(a, i).pipe(
   map((b, ii) => fn2(a, b, i, ii))
 )
)

您需要的行為已經可以通過重載SwitchMap和用於每個(outerValue,innerValue)的組合的 selectorFunc 實現:

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

我認為這是運營商

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();      
  });

請注意,take(1) 將關閉訂閱,但如果您希望用戶能夠多次按下按鈕,請將訂閱保存到 const 並在完成后取消訂閱。

有一個小技巧可以實現這一點 - 基本上你在 switchmap 中有一個全新的 observable,並且這個 observable 可以訪問傳遞給 switchmap 函數的值。 您可以在內部映射中使用此值來保留該值。

this.ticker$
  .switchMap(ticker => this.showHand$.pipe(map( (hand) => { ticker,hand } )))
  .subscribe( obj => {
     // use value here
     this.order.price = obj.ticker;
     this.order.amount = obj.hand.amount;
     this.order.type = obj.hand.type;

     this.submit();
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM