pixel
pixel

Reputation: 26441

Reactor apply Flux to each emission of other Flux?

I have two Flux objects eg.:

Flux<Item> and Flux<Transformation>

data class Item(val value: Int)

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

I would like to apply all transformations to each item - something like:

var item = Item(15)

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

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

but when having Flux'es of Item and Transformation

Upvotes: 0

Views: 587

Answers (1)

Alexander Pankin
Alexander Pankin

Reputation: 3955

You could use java.util.function.UnaryOperator instead of Transformation class. Hope this Java example could help you:

@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;
}

Upvotes: 3

Related Questions