Reactor - 在flatMap的输出上调用块会导致ClassCastException

我正在使用Spring Boot 2.0.0.M7和Project Reactor。我的问题涉及编写单元测试时遇到的一些奇怪的行为。在尝试将flatMap的输出提供给存储库时,我也遇到了这个问题。Reactor - 在flatMap的输出上调用块会导致ClassCastException

Mono<Foo> create(Mono<FooResource> resourceMono) { 

resourceMono.flatMap({

// convert resource into Foo domain Entity

return new Foo()

})

}

该闭合应该发出Mono<Foo>由于flatMap返回值。但是,调用block()时认购并获得所产生的Foo,有一个ClassCastExceptionFluxFlatMap.trySubscribeScalarMap

测试代码:

def createdFoo = Foo.create(Mono.just(fooResource)).block() 

堆栈跟踪:

java.lang.ClassCastException: com.example.Foo cannot be cast to org.reactivestreams.Publisher 

at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:141)

at reactor.core.publisher.MonoFlatMap.subscribe(MonoFlatMap.java:53)

at reactor.core.publisher.Mono.block(Mono.java:1161)

这似乎发生,因为MonoJust工具Callable,所以trySubscribeScalarMap试图解开它不成功。

在非测试案例场景中,会发生类似的错误。

Mono<ServerResponse> createFoo(ServerRequest request) { 

def body = request.body(BodyExtractors.toMono(FooResource))

ok().body(fromPublisher(Foo.create(body)

.flatMap({fooRepository.save(it)}), Foo))

}

堆栈跟踪:

java.lang.ClassCastException: com.example.Foo cannot be cast to reactor.core.publisher.Mono 

at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:118) [reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]

at reactor.core.publisher.FluxOnAssembly$OnAssemblySubscriber.onNext(FluxOnAssembly.java:450) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]

at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1092) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]

at reactor.core.publisher.MonoSingle$SingleSubscriber.onComplete(MonoSingle.java:171) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]

<...>

Assembly trace from producer [reactor.core.publisher.MonoFlatMap] :

reactor.core.publisher.Mono.flatMap(Mono.java:2059)

org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap.invoke(PojoMetaMethodSite.java:213)

org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)

org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)

org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)

org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)

com.example.Foo.create(Foo.groovy:28)

org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)

org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)

org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)

com.example.FooHandlerFunctions.createFoo(FooHandlerFunctions.groovy:48)

中包装flatMap封闭的输出在另一Mono.just(foo)解决了这两个问题。但是,这似乎不应该需要。我做错了什么,或者只是误解flatMap在这里工作?

回答:

flatmap需要Function应该返回一个Mono(我猜时髦让你返回错误类型,如Foo似乎并没有实现Publisher?)

以上是 Reactor - 在flatMap的输出上调用块会导致ClassCastException 的全部内容, 来源链接: utcz.com/qa/265856.html

回到顶部