Home > Enterprise >  How to resolve method 'getT1' in 'Void'
How to resolve method 'getT1' in 'Void'

Time:11-07

I have the following method:

public void countLetters() {
    Flux.just("alpha", "bravo", "charlie")
            .map(String::toUpperCase)
            .flatMap(s -> Flux.fromArray(s.split("")))
            .groupBy(String::toString)
            .sort(Comparator.comparing(GroupedFlux::key))
            .flatMap(group -> Mono.just(group.key()).and(group.count()))
            .map(keyAndCount ->
                    keyAndCount.getT1()   " => "   keyAndCount.getT2())
            .subscribe(System.out::println);
}

It gives me these errors:

Cannot resolve method 'getT1' in 'Void'

Cannot resolve method 'getT2' in 'Void'

I'm not sure what this means. Is it because my method is void or is it some other reason?

CodePudding user response:

Instead of

            .flatMap(group -> Mono.just(group.key()).and(group.count()))

You need

            .map(group -> new Tuple2<>(group.key(), group.count()))

The issues in your flatMap:

  • It doesn't need to be a flat map at all. You are mapping your response in a "1 to 1" fashion without any further reactive streams, so the Mono.just isn't needed.
  • Mono.and joins 2 Monos and will produce a new Mono<Void> which is a mono that only completes (when all joined monos complete), meaning it has no result (doesn't emit any values). This means that .map and .flatMap on this mono will accept a Void as param (main reason for your compile time error). Not just that, but they will never be called, as Mono<Void> don't emit any Void values, they just complete (similar to Completable from RxJava).

For example, if you have

Mono<File> downloadFile = ...;
Mono<Long> calculateNumber = ...;

and you perform

Mono<Void> test = downloadFile.and(calculateNumber);

You would create a new Mono that completes when both monos complete, but throws away both values!

So:

test.map(v -> {
   // v is type of "Void", and this map will never be called!
   System.out.println("this will never be printed!");
   return 0;
}).doFinally((signalType) -> {
            System.out.println("this will be called!");
        }).subscribe(
                v -> System.out.println("wont be called, nothing is emitted!"),
                err -> System.out.println("this might be called, if the stream emits an error"),
                () -> System.out.println("this will be called, as its a completion handler!")
        );

The mono test will terminate/complete after both monos joined with and complete.

If you really want a flatMap with Mono.just-ing the values of the tuple, you could use Mono.zip.

  • Related