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

问题描述 投票:0回答:1

我有两个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) 
  }
}

但当有Flux'es的ItemTransformation

kotlin project-reactor
1个回答
3
投票

您可以使用java.util.function.UnaryOperator而不是Transformation类。希望这个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;
}
© www.soinside.com 2019 - 2024. All rights reserved.