如何根据列表项中的先前排放删除重复项

How remove duplicates based on previous emission in List item

我有一个 ObservableLists:

Observable<List<String>> source = Observable.just(
        List.of("a", "c", "e"),
        List.of("a", "b", "c", "d"),
        List.of("d", "e", "f")
);

如何删除重复项:

[a,c,e][a,b,c,d][d,e,f] => [a,c,e][b,d][f]

我之前的排放积累起来还可以,只需要像上面那样改造。

我用 scan 运算符和助手 class 实现了它,它存储当前和以前的值:

static class Distinct {
    final HashSet<String> previous;
    final List<String> current;

    public Distinct(HashSet<String> previous, List<String> current) {
        this.previous = previous;
        this.current = current;
    }
}

Observable<List<String>> source = Observable.just(
        List.of("a", "c", "e"),
        List.of("a", "b", "c", "d"),
        List.of("d", "e", "f")
);

source.scan(new Distinct(new HashSet<>(), new ArrayList<>()), (acc, item) -> {
    var newItem = new ArrayList<String>();
    item.forEach(i -> {
        if (acc.previous.add(i))
            newItem.add(i);
    });
    return new Distinct(acc.previous, newItem);
})
        .skip(1)
        .map(md -> md.current)
        .subscribe(System.out::println);

输出:

[a, c, e]
[b, d]
[f]