将publishOn与自定义Publisher一起使用时,ReactiveStreams NPE

时间:2017-09-28 12:59:38

标签: kotlin reactive-streams

当我将自适应流(https://github.com/reactor/reactor-core)与自定义Publisher结合使用publishOn功能时,我总是会获得NPE。我的代码出了什么问题?我是否以错误的方式使用Publisher

Flux.from(MyPublisher())
            .publishOn(Schedulers.single())
            .subscribe { println("<-- $it received") }

class MyPublisher : Publisher<Int> {
    override fun subscribe(sub: Subscriber<in Int>) {
        while (true) {
            Thread.sleep(300)
            sub.onNext(1)
        }
    }
}

例外是:

Exception in thread "main" java.lang.NullPointerException
    at reactor.core.publisher.FluxPublishOn$PublishOnSubscriber.onNext(FluxPublishOn.java:212)
    at org.guenhter.kotlin.hello.MyPublisher.subscribe(HelloWorld.kt:18)
    at reactor.core.publisher.FluxSource.subscribe(FluxSource.java:52)
    at reactor.core.publisher.FluxPublishOn.subscribe(FluxPublishOn.java:96)
    at reactor.core.publisher.Flux.subscribe(Flux.java:6447)
    at reactor.core.publisher.Flux.subscribeWith(Flux.java:6614)
    at reactor.core.publisher.Flux.subscribe(Flux.java:6440)
    at reactor.core.publisher.Flux.subscribe(Flux.java:6404)
    at reactor.core.publisher.Flux.subscribe(Flux.java:6347)
    at org.guenhter.kotlin.hello.HelloWorldKt.main(HelloWorld.kt:11)

1 个答案:

答案 0 :(得分:2)

Publisher由&#34; reactive-streams&#34;定义。标准并有许多要求。其中一个要求是Subscriber.onSubscribe在任何其他方法之前被调用以遵循协议。

由于你还没有这样做,这意味着可能没有正确初始化的东西,导致反应堆类内的NPE。

但是,即使您解决了这个问题,标准也会被设计为被动,这意味着它只会在用户请求时发出数据。因为您将发送数据,无论这可能会导致稍后的异常。使用Flux.create创建一个可以正确处理请求的发射器,而不是创建自己的Publisher实现。