简体   繁体   English

如何为任何方法调用创建通用包装器?

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

I want to create a helper method that can wrap/convert just any sync method call into an async Mono .我想创建一个辅助方法,它可以将任何同步方法调用包装/转换为异步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
}

First you call Mono.fromCallable with a Callable<Callable<?首先你用 Callable<Callable<? extend T>>.扩展 T>>。 You need to change the call like this: Mono.fromCallable(supplier) .您需要像这样更改调用: Mono.fromCallable(supplier)

Then you will have a problem because Mono.fromCallable will be inferred as Callable<? extend ? extend T>那么你会遇到一个问题,因为 Mono.fromCallable 会被推断为Callable<? extend ? extend T> Callable<? extend ? extend T> Callable<? extend ? extend T> so your Mono will be Mono<? extend T> Callable<? extend ? extend T>所以你的 Mono 将是Mono<? extend T> Mono<? extend T> instead of Mono<T> . Mono<? extend T>而不是Mono<T> To avoid this, two solutions:为了避免这种情况,有两种解决方案:

  1. Change the signature of wrapAsync:更改 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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM