英文:
How to create a generic wrapper for just any method call?
问题
我想创建一个辅助方法,可以将任何同步方法调用包装/转换成异步的Mono
。
以下部分接近目标,但出现了一个错误:
所需类型:Mono<T>
提供类型:Mono<? extends Callable<? extends T>>
这是我的代码:
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; //仅用于测试
}
英文:
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
}
答案1
得分: 3
以下是翻译好的内容:
首先,您使用一个类型为 Callable<Callable<? extend T>> 的 Callable 调用 Mono.fromCallable。您需要将调用更改为这样:Mono.fromCallable(supplier)
。
然后,您会遇到一个问题,因为 Mono.fromCallable 将被推断为 Callable<? extend ? extend T>
,所以您的 Mono 将是 Mono<? extend T>
,而不是 Mono<T>
。为了避免这种情况,有两种解决方案:
- 更改 wrapAsync 的签名:
public <T> Mono<T> wrapAsync(Callable<T> supplier) {
return Mono.fromCallable(supplier)
.subscribeOn(Schedulers.boundedElastic());
}
- 或者,如果您想保留签名,您需要提供类型:
public <T> Mono<T> wrapAsync(Callable<? extends T> supplier) {
return Mono.<T>fromCallable(supplier)
.subscribeOn(Schedulers.boundedElastic());
}
英文:
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:
- Change the signature of wrapAsync:
public <T> Mono<T> wrapAsync(Callable<T> supplier) {
return Mono.fromCallable(supplier)
.subscribeOn(Schedulers.boundedElastic());
}
- 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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论