你能不能压缩一个单声道和一个磁通,并为每个磁通值重复这个单声道的值?
是否可以执行类似以下代码的操作?我有一个进行API调用的服务和另一个返回值流的服务。我需要根据API调用返回的值修改每个值。
return Flux.zip(
someMono.get(),
someFlux.Get(),
(d, t) -> {
//HERE D IS ALWAYS THE SAME AND T IS EVERY NEW FLUX VALUE
});
我尝试对Mono使用.Repeat(),但它在每次有新的Flux值时都会调用该方法,而且它是一个API调用,所以它不是很好。
可以吗?
解决方案
这将说明如何将助焊剂与单声道组合在一起,以便每次助焊剂发射时,单声道也会发射。
假设您有一个通量和一个单声道,如下所示:
// a flux that contains 6 elements.
final Flux<Integer> userIds = Flux.fromIterable(List.of(1,2,3,4,5,6));
// a mono of 1 element.
final Mono<String> groupLabel = Mono.just("someGroupLabel");
首先,我将向您展示我尝试过的压缩2的错误方法,我想其他人也会尝试:
// wrong way - this will only emit 1 event
final Flux<Tuple2<Integer, String>> wrongWayOfZippingFluxToMono = userIds
.zipWith(groupLabel);
// you'll see that onNext() is only called once,
// emitting 1 item from the mono and first item from the flux.
wrongWayOfZippingFluxToMono
.log()
.subscribe();
// this is how to zip up the flux and mono how you'd want,
// such that every time the flux emits, the mono emits.
final Flux<Tuple2<Integer, String>> correctWayOfZippingFluxToMono = userIds
.flatMap(userId -> Mono.just(userId)
.zipWith(groupLabel));
// you'll see that onNext() is called 6 times here, as desired.
correctWayOfZippingFluxToMono
.log()
.subscribe();
相关文章