首页 > 解决方案 > 在 rxjs 中选择重复列表的最后一项

问题描述

我从一个 Socket 中得到一堆流,并想选择最新的项目。

我知道distinctUntilChanged正在选择第一项,但我需要以某种方式反转此功能。

总之,我想通过 rxjs 做到这一点:

In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: - - - - 1 - - - 2 - - - 3 - - - - - 1 - - - - - 2 - 1 - - - 2 - 3 - -

标签: javascriptsocketsmergerxjsdistinct

解决方案


我们可以在更改后发出最后一个值:

In:  1 - 1 - 1 - 2 - 2 - 3 - 3 - 1 - 1 - 1 - 2 - 2 - 2 - 1 - 2 - 2 - 3 - 3
Out: - - - - - - 1 - - - 2 - - - 3 - - - - - 1 - - - - - 2 - 1 - - - 2 - 3

import { pairwise, take, filter, map, merge, last } from 'rxjs/operators';
import { interval, from } from 'rxjs';

const stream$ = from([1, 1, 1, 2, 2, 3, 3, 1, 1, 1, 2, 2, 2, 1, 2, 2, 3, 3]);

stream$
  .pipe(
    pairwise(),
    filter(([prev, cur]) => prev !== cur),
    map(([prev, cur]) => prev),
    merge(stream$.pipe(last()))
  )
  .subscribe(console.log);

推荐阅读