【问题标题】:RxJS function that emit last value from one observable then other emit trueRxJS 函数从一个 observable 发出最后一个值,然后另一个发出 true
【发布时间】:2018-01-18 23:35:08
【问题描述】:

您好,我正在尝试创建可观察(OBS)和主题(SUB)的函数,用于存储来自 OBS 的最后一项,而 SUB 具有 F 值, 当 SUN 变为 T 时发射它(并且只发射它)

   OBS ---a----b----c----d----e----f----g----h-----
   SUB ------F----------T------------F-------T-----
   OUT -----------------c--------------------h-----

我试图解决这个问题

OBS.window(SUB)
        .withLatestFrom(SUB)
        .switchMap(([window, status]) => {

            if(status === F) {
                return window.combineLatest(SUB, (cmd, status) => {
                    if(status === T) {
                        return null;
                    };

                    return cmd;
                }).last((e) => {
                    return !!e;
                })
            }

            return Observable.empty<Command>();
        }).filter((cmd) => {
            return !!cmd;
        })

但它不起作用

【问题讨论】:

  • 如果SUB 连续发出两个Ts,当SUBF 时,结果observable 是否仍会产生最后收到的值?
  • @SergeyKaravev,不,但可以用 distinctUntilChanged 修复

标签: javascript typescript rxjs rxjs5


【解决方案1】:

所以看起来你想要这样的东西:

SUB
  // Only emit changes in the status
  .distinctUntilChanged()
  // Only forward true values down stream
  .filter(t => t === T)
  // Only emit the latest from OBS when you get a T from SUB
  // Remap it so only cmd is forwarded
  .withLatestFrom(OBS, (_, cmd) => cmd)

【讨论】:

    【解决方案2】:

    我找到了自己的解决方案:

    OBS
        .buffer(SUB)
        .withLatestFrom(SUB)
        .map(([buffer, t]) => {
            if(!buffer || !buffer.length) {
                return null;
            }
    
            if(t === T) {
                return buffer[buffer.length - 1];
            }
    
            return null;
        })
        .filter((e) => !!e);
    

    这个变种有下一个行为

     ---a----b----c----d----e----f----g----h-----
     ------F----------T------------F-------T-----
     -----------------c--------------------h-----
    

    如果 F 和 T 之间的窗口为空,则不生成输出

     ---a--------------d----e----f----g----h-----
     ------F----------T------------F-------T-----
     --------------------------------------h-----
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2020-09-27
      • 2017-12-17
      • 1970-01-01
      相关资源
      最近更新 更多