springboot webflux flux 使用示例(创建操作)
*************************
just、defer
public class Test {
public static void main(String[] args) throws Exception{
Flux.defer(() -> Flux.just("hello world "+System.currentTimeMillis()))
.delaySubscription(Duration.ofSeconds(2))
.subscribe(s -> {
System.out.println(s);
System.out.println("hello world "+System.currentTimeMillis());
});
Flux.just("hello world2 "+System.currentTimeMillis())
.delaySubscription(Duration.ofSeconds(2))
.subscribe(s -> {
System.out.println(s);
System.out.println("hello world2 "+System.currentTimeMillis());
});
TimeUnit.SECONDS.sleep(6);
}
}
********************
控制台输出
hello world 1593229538551
hello world 1593229538555
hello world2 1593229536538
hello world2 1593229538555
defer当订阅的时候创建flux对象流,just立刻创建对象流
*************************
from
public class Test2 {
public static void main(String[] args){
String[] s=new String[2];
s[0]="瓜田李下";
s[1]="瓜田李下 2";
Flux.fromArray(s).subscribe(System.out::println);
System.out.println("\n****************");
List<String> list=new ArrayList<>();
list.add("瓜田李下");
list.add("瓜田李下 2");
Flux.fromIterable(list).subscribe(System.out::println);
System.out.println("\n****************");
Map<Integer,String> map=new HashMap<>();
map.put(1,"瓜田李下");
map.put(2,"瓜田李下 2");
map.put(3,"瓜田李下 3");
Flux.fromIterable(map.entrySet()).subscribe(entry -> System.out.println(entry.getKey()+" ==> "+entry.getValue()));
}
}
********************
控制台输出
瓜田李下
瓜田李下 2
****************
瓜田李下
瓜田李下 2
****************
1 ==> 瓜田李下
2 ==> 瓜田李下 2
3 ==> 瓜田李下 3
*************************
concat、merge
public class Test3 {
public static void main(String[] args){
Flux.concat(Flux.just("瓜田李下","瓜田李下 2")).subscribe(System.out::println);
System.out.println("\n*************");
Flux.merge(Flux.just("hello world","hello world 2")).subscribe(System.out::println);
}
}
********************
控制台输出
瓜田李下
瓜田李下 2
*************
hello world
hello world 2
*************************
zip、combineLatest
public class Test4 {
public static void main(String[] args){
Flux.zip(Flux.just("hello world "),Flux.just("2"),(value1,value2) -> value1+value2)
.subscribe(System.out::println);
Flux.combineLatest(Flux.just("hello world"),Flux.just("3"),Flux.just("4"),
array -> {
StringBuilder result= new StringBuilder();
for (Object o : array) {
result.append(o).append(" ");
}
return result.toString();
}).subscribe(System.out::println);
}
}
********************
控制台输出
hello world 2
hello world 3 4