我正在学习反应流并在Publishers(Flux)上工作,并致力于Flux的转型。为此,我得到了撰写和转换方法。
这是我的代码:
var a = "1,2,3,4,foo,bar";
var b = a.split(',');
var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.
// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.
这是输出,两种情况都是相同的:
private static void composeStream() {
System.out.println("*********Calling composeStream************");
Function<Flux<String>, Flux<String>> alterMap = f -> {
return f.filter(color -> !color.equals("ram"))
.map(String::toUpperCase);
};
Flux<String> compose = Flux.fromIterable(Arrays.asList("ram", "sam", "kam", "dam"))
.doOnNext(System.out::println)
.compose(alterMap);
compose.subscribe(d -> System.out.println("Subscriber to Composed AlterMap :"+d));
System.out.println("-------------------------------------");
}
private static void transformStream() {
System.out.println("*********Calling transformStream************");
Function<Flux<String>, Flux<String>> alterMap = f -> f.filter(color -> !color.equals("ram"))
.map(String::toUpperCase);
Flux.fromIterable(Arrays.asList("ram", "sam", "kam", "dam"))
.doOnNext(System.out::println)
.transform(alterMap)
.subscribe(d -> System.out.println("Subscriber to Transformed AlterMap: "+d));
System.out.println("-------------------------------------");
}
两者有什么区别? 请建议
答案 0 :(得分:6)
转换此
B
以生成目标Flux
。与Flux
不同,提供的函数作为汇编的一部分执行。
如果我们要写下一个小测试:
Flux#compose(Function)
在输出中我们将观察下一个结果:
int[] counter = new int[1];
Function transformer = f -> {
counter[0]++;
return f;
}
Flux flux = flux Flux.just("")
.transform(transformer);
System.out.println(counter[0]);
flux.subscribe();
flux.subscribe();
flux.subscribe();
System.out.println(counter[0]);
这意味着变换函数将在组装管道期间执行一次,换句话说,转换函数将执行 急切 。
反过来,使用 1
1
,我们将获得相同代码的下一个行为
.compose
输出
int[] counter = new int[1];
Function transformer = f -> {
counter[0]++;
return f;
}
Flux flux = flux Flux.just("")
.compose(transformer);
System.out.println(counter[0]);
flux.subscribe();
flux.subscribe();
flux.subscribe();
System.out.println(counter[0]);
这意味着对于每个订阅者,转换功能将单独执行,我们可能会将此类执行视为 lazy