How to create a generic wrapper for just any method call?

Tags: , , , ,



I want to create a helper method that can wrap/convert just any sync method call into an async Mono.

The following is close, but shows an error:

Required type: Mono <T>
Provided: Mono<? extends Callable<? extends T>>

This is my code:

public <T> Mono<T> wrapAsync(Callable<? extends T> supplier) {
    return Mono.fromCallable(() -> supplier)
            .subscribeOn(Schedulers.boundedElastic());
}

public void run() {
    Mono<Boolean> mono = wrapAsync(() -> syncMethod());
}

private Boolean mySyncMethod() {
    return true; //for testing only
}

Answer

First you call Mono.fromCallable with a Callable<Callable<? extend T>>. You need to change the call like this: Mono.fromCallable(supplier).

Then you will have a problem because Mono.fromCallable will be inferred as Callable<? extend ? extend T> so your Mono will be Mono<? extend T> instead of Mono<T>. To avoid this, two solutions:

  1. Change the signature of wrapAsync:
public <T> Mono<T> wrapAsync(Callable<T> supplier) {
    return Mono.fromCallable(supplier)
            .subscribeOn(Schedulers.boundedElastic());
}
  1. Or if you want to keep the signature you need to provide type:
public <T> Mono<T> wrapAsync(Callable<? extends T> supplier) {
    return Mono.<T>fromCallable(supplier)
            .subscribeOn(Schedulers.boundedElastic());
}


Source: stackoverflow