反应堆是否将通量应用于其他每个通量?

时间:2019-03-13 18:11:53

标签: kotlin project-reactor

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

但是当有FluxItem的{​​{1}}时

1 个答案:

答案 0 :(得分: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;
}