如何根据流中的元素动态划分连续的RXJava流?

时间:2019-04-06 15:07:26

标签: java rx-java rx-java2

最简单的示例是这样的字符串流:

["3", "a", "b", "c", "1", "a", "2", "a", "b"]

数字表示该分组应包含多少元素。

非常重要的一点是流是连续的,因此我们不能只等待下一个数字来拆分流。

据我所知,RXJava2中没有为此内置的功能

var flowable = Flowable.concat(Flowable.fromArray("3", "a", "b", "c", "1", "a", "2", "a", "b"), Flowable.never());

flowable/*Something here*/.blockingSubscribe(System.out::println);

预期输出为:

[3, a, b, c]
[1, a]
[2, a, b]

1 个答案:

答案 0 :(得分:2)

我后来找到了akarnokd的RxJava2Extensions软件包。使用它,我能够构造它,它可以实现我想要的:


var flowable = Flowable.concat(Flowable.fromArray("3", "a", "b", "c", "1", "a", "2", "a", "b"), Flowable.never());
flowable.compose(FlowableTransformers.bufferUntil(new Predicate<>() {
    private int remaining = 0;
    @Override
    public boolean test(String next) {
        if(next.chars().allMatch(Character::isDigit)) {
            remaining = Integer.parseInt(next);
        }
        return --remaining < 0;
    }
})).blockingSubscribe(System.out::println);