将一个通量分成两个通量 - 头和尾 [英] Split a flux into two fluxes - head and tail
问题描述
我想将一个通量拆分为两个通量,其中第一个通量具有原始通量的第一项,第二个通量将获得其余项.
I want to split a flux into two fluxes where the first one has the first item of the original flux and the second one will takes the rest of items.
在每个通量上应用自定义转换 myLogic
后,我想将它们组合成一个通量,保留原始通量的顺序.
After applying a custom transformation myLogic
on each flux I want to combine them into one flux preserving the order of the original flux.
示例:
S:学生
S':申请myLogic
发射通量:s1 ->s2 ->s3 ->s4
第一个分裂通量:s1' =>myLogic
第二个分裂通量:s2' ->s3' ->s4' =>myLogic
组合通量:s1' ->s2' ->s3' ->s4'
推荐答案
使用标准的 Flux
方法 take
和 skip
就足够了分离头和尾元素.在此之前调用 cache
也有助于避免订阅重复.
It is enough to use standard Flux
methods take
and skip
to seprate head and tail elements. Calling cache
before that is also useful to avoid subscription duplication.
class Util {
static <T, V> Flux<V> dualTransform(
Flux<T> originalFlux,
int cutpointIndex,
Function<T, V> transformHead,
Function<T, V> transformTail
) {
var cached = originalFlux.cache();
var head = cached.take(cutpointIndex).map(transformHead);
var tail = cached.skip(cutpointIndex).map(transformTail);
return Flux.concat(head, tail);
}
static void test() {
var sample = Flux.just("a", "b", "c", "d");
var result = dualTransform(
sample,
1,
x -> "{" + x.toUpperCase() + "}",
x -> "(" + x + ")"
);
result.doOnNext(System.out::print).subscribe();
// prints: {A}(b)(c)(d)
}
}
这篇关于将一个通量分成两个通量 - 头和尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!