java—在步长大于1的范围内发出整数对的最佳方法

gab6jxml  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(348)

我想在rxjava2中处理整数的范围,我正在寻找最优雅的方法来解决它。暴力解决方案( processRange 函数只是一个占位符,实际上,处理from/to变量要复杂得多—您可以将其视为来自数据库的分页,需要在特定大小的块中访问才能执行):

public static Flowable<Object> processRange(int from, int to) {
    return Flowable.just("From:" + from + " to:" + to);
}

public static void main(String[] args) {

    int start = 333;
    int end = 78777;
    int step = 1000;

    List<Pair<Integer, Integer>> ranges = Lists.newArrayList();
    for (int i = start; i < end; i += step) {
        ranges.add(Pair.of(i, Math.min(i + step - 1, end)));
    }

    Flowable.concat(
            ranges.stream()
                    .map(range -> processRange(range.getLeft(), range.getRight())).collect(Collectors.toList()))
            .forEach(System.out::println);
}

我认为这真的是一种丑陋的实现方式。我提出了一些重用rxjava的东西,但它仍然非常冗长和神秘

int start = 333;
    int end = 78777;
    int step = 1000;

    int count = (end-start-1)/step + 1;

    Flowable.concat(
            Flowable.range(0,count)
                    .map(idx -> processRange(start+idx*step,Math.min(start+((idx+1)*step)-1,end))))
            .forEach(System.out::println);

最坏的情况是,我将把它全部隐藏在一个方法中,然后对它进行单元测试,但也许我正在撬开一扇打开的门,有更简单的方法可用吗?

qpgpyjmq

qpgpyjmq1#

你可以举个例子 create() 操作员:

class SO65163142 {
    public Flowable<String> processRange(int from, int to) {
        return Flowable.just("From:" + from + " to:" + to);
    }

    public Flowable<String> getRanges(int start, int end, int step) {
        return Flowable
                .create((FlowableOnSubscribe<Pair<Integer, Integer>>) emitter -> {
                    int current = start;

                    while (current + step < end) {
                        emitter.onNext(new Pair<>(current, current + step - 1));
                        current += step;
                    }

                    emitter.onNext(new Pair<>(current, end));
                    emitter.onComplete();
                }, BackpressureStrategy.BUFFER)
                .flatMap(pair -> processRange(pair.first, pair.second));
    }
}

确保根据需要应用一些+/-1补偿。一些验证:

public class SO65163142Test {

    @Test
    public void getRangesTest() {
        SO65163142 tested = new SO65163142();

        int start = 333;
        int end = 4777;
        int step = 1000;

        TestSubscriber<String> testSubscriber = tested
                .getRanges(start, end, step)
                .test();

        testSubscriber.assertValues(
                "From:333 to:1332",
                "From:1333 to:2332",
                "From:2333 to:3332",
                "From:3333 to:4332",
                "From:4333 to:4777"
        );
    }
}

相关问题