我得到一个Publisher<DataBuffer> inputStream
作为参数。我想将该流转换为字符串,记录该字符串,然后必须将该字符串作为Publisher
再次传递给另一种方法。
示例:
public Flux<Object> decode(Publisher<DataBuffer> inputStream) {
return DataBufferUtils.join(inputStream)
.map(buffer -> StandardCharsets.UTF_8.decode(buffer.asByteBuffer()).toString())
.doOnNext(arg -> LOGGER.info(arg))
.map(arg -> library.delegate(Mono.fromSupplier(() -> arg)))
.flatMapIterable(arg -> {
System.out.println(arg); //instanceof FluxLift??
return List.of(arg);
);
}
class ExternalLibrary {
//this ALWAYS returns a FluxLift
public Flux<Object> delegate(Publisher<String> inputString) {
//does not matter, I don't have control of this.
//lets assume it does the following:
return Flux.just(input).
flatMapIterable(buffer -> List.of("some", "result"))
.map(arg -> arg);
}
}
问题:为什么最后一个flatMapInterable()
中的参数总是为FluxLift
类型?而且:如何在这里返回实际值?
答案 0 :(得分:1)
为什么最终的flatMapInterable()中的参数始终为FluxLift类型?
因为您的地图函数返回Flux
.map(arg -> library.delegate(Mono.fromSupplier(() -> arg)))
如何在这里返回实际值?
当映射函数返回反应类型时,请使用flatMap*
函数之一而不是map
。 flatMapMany
适合您的情况:
public Flux<Object> decode(Publisher<DataBuffer> inputStream) {
return DataBufferUtils.join(inputStream) //Mono<DataBuffer>
.map(buffer -> StandardCharsets.UTF_8.decode(buffer.asByteBuffer()).toString()) //Mono<String>
.doOnNext(arg -> LOGGER.info(arg)) //Mono<String>
.flatMapMany(arg -> library.delegate(Mono.fromSupplier(() -> arg))) // Flux<Object>
.flatMapIterable(arg -> {
System.out.println(arg); // instanceof Object
return List.of(arg);
);