Reactor 将 Flux 应用于其他 Flux 的每次发射?

Reactor apply Flux to each emission of other Flux?

我有两个 Flux 对象,例如:

Flux<Item>Flux<Transformation>

data class Item(val value: Int)

data class Transformation(val type: String, val value: Int)

我想对每个项目应用所有转换 - 例如:

var item = Item(15)

val transformations = listOf(Transformation(type = "MULTIPLY", value = 8), ...)

transformations.forEach {
  if (it.type == "MULTIPLY") {
    item = Item(item.value * it.value) 
  }
}

但是当有 ItemTransformationFlux

您可以使用 java.util.function.UnaryOperator 而不是 Transformation class。 希望这个 Java 示例可以帮助您:

@Test
public void test() {
    Flux<Item> items = Flux.just(new Item(10), new Item(20));
    Flux<UnaryOperator<Item>> transformations = Flux.just(
            item -> new Item(item.value * 8),
            item -> new Item(item.value - 3));

    Flux<Item> transformed = items.flatMap(item -> transformations
            .collectList()
            .map(unaryOperators -> transformFunction(unaryOperators)
                    .apply(item)));

    System.out.println(transformed.collectList().block());
}

Function<Item, Item> transformFunction(List<UnaryOperator<Item>> itemUnaryOperators) {
    Function<Item, Item> transformFunction = UnaryOperator.identity();
    for (UnaryOperator<Item> itemUnaryOperator : itemUnaryOperators) {
        transformFunction = transformFunction.andThen(itemUnaryOperator);
    }
    return transformFunction;
}