管道/过滤某些事件序列的奇特方式

问题描述 投票:0回答:1

假设我有一个返回随机数的可观察值,我只想了解它的每 2 次(或第 n 次)出现,我现在会编写以下过滤器:

import { interval, of } from 'rxjs';
import { filter, map, tap } from 'rxjs/operators';

let highValue = false;

interval(100)
  .pipe(
    map((v) => Math.random()),
    tap((v) => console.log(v)),
    filter((v) => {
      if (v > 0.9) {
        if (highValue) {
          highValue = false;
          return true;
        } else {
          highValue = true;
          return false;
        }
      }

      return false;
    })
  )
  .subscribe((v) => {
    console.warn(v);
  });

堆栈闪电战

有人可以建议一个更成熟的解决方案吗?

(我希望这不要太基于意见,但恕我直言,如果知道正确的操作员,我当前的解决方案可以相当简化。)

rxjs
1个回答
0
投票

扫描+过滤器+地图是一个非常典型的解决方案:

interval(200)
  .pipe(
    map(() => Math.random()),
    // compute whether to notify based on previous values
    scan((acc, value) => {
      const isHigh = value > 0.9
      const notify = isHigh && !acc.notify
      return {
        value,
        notify
      }
    }, { notify: false }),
    // filter to just the ones you want to notify on
    filter(({notify}) => notify),
    // transform the data back to the actual value (remove the book-keeping info)
    map(({value}) => value)
  )
  .subscribe(v => console.warn(v))
© www.soinside.com 2019 - 2024. All rights reserved.