如何将订阅者与reactor.core.publisher.Flux连接?

时间:2017-08-07 15:24:42

标签: java project-reactor

我想将订户与Reactor Flux连接起来。但是我的小例子没有产生任何输出:

public static void main(String[] args) throws InterruptedException {
    Flux.just("a", "b", "c")
            .subscribe(new BaseSubscriber<String>() {
                @Override
                protected void hookOnSubscribe(Subscription ignored) {
                }

                @Override
                protected void hookOnNext(String value) {
                    System.out.print(value);
                }
            });
    Thread.sleep(1000);
}

我尝试使用org.reactivestreams.Subscriber

    Flux.just("a", "b", "c")
            .subscribe(new Subscriber<String>() {
                @Override
                public void onSubscribe(Subscription s) {
                }

                @Override
                public void onNext(String s) {
                    System.out.println(s);
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onComplete() {
                }
            });

但同样,没有输出。

如果我尝试最简单的:

Flux.just("a", "b", "c").subscribe(System.out::println);

...它产生预期的输出:

a
b
c

如何使用订阅者接收Flux中的值?

1 个答案:

答案 0 :(得分:2)

关键是request来自源的更多值。在那之前没有任何事情发生。

BaseSubscriber的示例:

Flux<String> source = Flux.just("a", "b", "c");
source.subscribe(new BaseSubscriber<String>() {
            @Override
            protected void hookOnSubscribe(Subscription subscription) {
                request(1); // <-- here
            }

            @Override
            protected void hookOnNext(String value) {
                request(1); // <-- here
                System.out.println(value);
            }
        });

与标准Subscriber相同:

Flux<String> source = Flux.just("a", "b", "c");
source.subscribe(new Subscriber<String>() {
    private Subscription subscription;

    @Override
    public void onSubscribe(Subscription subscription) {
        this.subscription = subscription;
        subscription.request(1); // <-- here
    }

    @Override
    public void onNext(String s) {
        subscription.request(1); // <-- here
        System.out.println(s);
    }

    @Override
    public void onError(Throwable t) {
    }

    @Override
    public void onComplete() {
    }
});