在rxjava中打开和克隆边界的缓冲区

时间:2017-08-12 22:52:21

标签: java rx-java rx-java2

我正在尝试使用rxjava中打开和克隆边界的缓冲区,但是我无法使其工作。我想做的是假设一个可观察的发射,0,1,2,3,0,1,3,0,3我想以{0,1,2,3},{0,1结束,3},{0,3}。

这是我到目前为止的代码:

PublishSubject openning = PublishSubject.create();
        openning.doOnNext(new Consumer() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                if(o.equals("0"))
                    openning.onNext(o);
            }
        });

        Observable<String> observableA = Observable.interval(1, TimeUnit.SECONDS).map(value -> String.valueOf(value  % 10));

        observableA.subscribe(openning);
        // TODO: Buffer by boundary
        observableA = observableA.buffer(openning, new Function<String, Observable<List<String>>>() {
            @Override
            public Observable<List<String>> apply(@NonNull String o) throws Exception {
                list.add(o);
                if (o.equals("0")) {
                    return Observable.just(list);
                } else {
                    list.add(o);
                    sb.append(o);
                    return Observable.never();
                }
            }
        }, new Callable() {
            @Override
            public Object call() throws Exception {
                return list;
            }
        });

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:5)

如果您的意思是缓冲区应在遇到3之后重新启动,请查看RxJava 2的extensions project中的bufferUntil运算符。

compile "com.github.akarnokd:rxjava2-extensions:0.17.5"

Flowable.just("1", "2", "#", "3", "#", "4", "#")
.compose(FlowableTransformers.bufferUntil(v -> "#".equals(v)))
.test()
.assertResult(
    Arrays.asList("1", "2", "#"),
    Arrays.asList("3", "#"),
    Arrays.asList("4", "#")
);

对于1.x,rxjava-extrasTransformers.toListUntil()