4

I am very new to reactive-streams, Can someone help me to convert Mono<MyClass> to Flux<Integer>

I tried something like this -

Flux<Integer> myMethod(Mono<MyClass> homeWork) {
    return homeWork.map(h -> h.multiplicands)
              .flatMapMany(Flux::fromIterable).map(m -> h*m);
}
public class MyClass{
    int multiplier;
    List<Integer> multiplicands;
}

I am expecting the result of multiplier * (each) multiplicand in Flux<Integer> format.

Can you help me with the correct way of doing this?

Vinipuh007
  • 364
  • 2
  • 12
user3595026
  • 560
  • 2
  • 9
  • 26

1 Answers1

3

Transform the instance of MyClass into a Stream<Integer> which contains multiplied integers and then turn Mono<Stream<Integer>> into Flux<Integer>:

Flux<Integer> myMethod(Mono<MyClass> homeWork) {
  return homeWork
           .map(hw -> hw.multiplicands.stream().map(m -> m * hw.multiplier))
           .flatMapMany(Flux::fromStream);
}
Ilya Zinkovich
  • 4,082
  • 4
  • 25
  • 43
  • it worked, thanks for the answer. I have another question- Let's say if I have another property `List results;` in `MyClass` and I want to update the multiplication results to `results` property. How to do that? -Thanks – user3595026 May 17 '19 at 22:15
  • You can do it in the map function, collecting the stream beforehand. However, I wouldn’t recommend changing state inside pipeline operations. It’s much safer to produce a new object with required charachteristics. – Ilya Zinkovich May 17 '19 at 23:20