RxJS,Observable,如何保留价值并将地图切换到另一个地图 [英] RxJS, Observable, how to preserve value and switch map to another one

查看:59
本文介绍了RxJS,Observable,如何保留价值并将地图切换到另一个地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

我认为这是运营商

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中,并在完成后取消订阅.

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.

这篇关于RxJS,Observable,如何保留价值并将地图切换到另一个地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆