当我提取各个步骤并单独执行它们时,我创建的反应器变换函数不会给出相同的结果。
我有包含价格类型列表的 DTO 记录。
public record CarrierDto(MetaData metaData, List<Daily> dailySeries) {
public record MetaData(String name, String information) {};
public record Daily(String date, Integer price) {};
}
Mono<CarrierDto>
我想从a中提取Flux<Daily>
然后将其转换为Flux<Price>
.
@Table("price")
public record Price (
@Column("p_date") String date,
@Column("p_price") Integer price) {
}
为了进行这种转换,我有这个功能:
static Function<Mono<CarrierDto>, Flux<Price>> transform = carrierDtoMono ->
carrierDtoMono.map(CarrierDto::dailySeries)
.flatMapMany(Flux::fromIterable)
.map(daily -> new Price(daily.date(), daily.price()));
然而,当我尝试使用此功能时,订阅时仅给出一个价格。如果我提取每个单独的步骤并执行提供的所有价格。例如这个测试类:
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class TestMain {
static Function<Mono<CarrierDto>, Flux<Price>> transform = carrierDtoMono ->
carrierDtoMono.map(CarrierDto::dailySeries)
.flatMapMany(Flux::fromIterable)
.map(daily -> new Price(daily.date(), daily.price()));
public static void main(String[] args) {
final CarrierDto dto = new CarrierDto(new CarrierDto.MetaData("Test", "Test information"),
Arrays.asList(new CarrierDto.Daily("2023-01-01", 100),
new CarrierDto.Daily("2023-01-02", 101),
new CarrierDto.Daily("2023-01-03", 102),
new CarrierDto.Daily("2023-01-04", 103)));
System.out.println("Using Transform function.");
Mono.just(dto)
.transform(transform)
.subscribe(price -> System.out.println(String.format("Date: %s Price: %d", price.date(), price.price())));
System.out.println("Without transform function.");
final Mono<List<CarrierDto.Daily>> monoDailySeries = Mono.just(dto).map(CarrierDto::dailySeries);
final Flux<CarrierDto.Daily> dailyFlux = monoDailySeries.flatMapMany(Flux::fromIterable);
final Flux<Price> priceFlux = dailyFlux.map(daily -> new Price(daily.date(), daily.price()));
priceFlux.subscribe(price -> System.out.println(String.format("Date: %s Price: %d", price.date(), price.price())));
}
}
给出结果:
Using Transform function.
Date: 2023-01-01 Price: 100
Without transform function.
Date: 2023-01-01 Price: 100
Date: 2023-01-02 Price: 101
Date: 2023-01-03 Price: 102
Date: 2023-01-04 Price: 103
为什么结果不同?
这是因为
transformer
inMono
生成一个新的Mono
,即仅向发布者请求第一项。其内部有:
我建议从 Flux 开始(或将 Mono 转换为 Flux)。就像你的例子一样: