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

huangapple go评论79阅读模式
英文:

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&lt;? extend ? extend T&gt;,所以您的 Mono 将是 Mono&lt;? extend T&gt;,而不是 Mono&lt;T&gt;。为了避免这种情况,有两种解决方案:

  1. 更改 wrapAsync 的签名:
public <T> Mono<T> wrapAsync(Callable<T> supplier) {
    return Mono.fromCallable(supplier)
            .subscribeOn(Schedulers.boundedElastic());
}
  1. 或者,如果您想保留签名,您需要提供类型:
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&lt;? extend ? extend T&gt; so your Mono will be Mono&lt;? extend T&gt; instead of Mono&lt;T&gt;. To avoid this, two solutions:

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

huangapple
  • 本文由 发表于 2020年10月20日 18:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64442953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定