gpt4 book ai didi

java - Spring Reactive - 重用Mono值

转载 作者:行者123 更新时间:2023-12-02 15:49:25 25 4
gpt4 key购买 nike

我使用 flatMap 进行了一系列 Mono 转换。我设法将我的生产代码简化为这个测试用例:

@Test
public void test() {
AtomicInteger iCounter = new AtomicInteger(1);
Mono<String> iValueMono = Mono.fromSupplier(() -> {
int iValue = iCounter.getAndIncrement();
System.out.println("iValueMono CALL: " + iValue);
return String.valueOf(iValue);
});

Mono<String> resultMono = Mono.just("X")
.flatMap(append(iValueMono))
.flatMap(append(iValueMono));

StepVerifier.create(resultMono)
.consumeNextWith(result -> assertThat(result).isEqualTo("X11"))
.expectComplete()
.verify();
}

private Function<String, Mono<String>> append(Mono<String> sMono) {
return s -> sMono.map(v -> s + v);
}

打印:

iValueMono CALL: 1
iValueMono CALL: 2

org.junit.ComparisonFailure:
Expected :"X11"
Actual :"X12"

我认为 - 我现在发现这是不正确的 - 每次我在 append() 调用中映射 iValueMono 时,供应商都会重新执行以生成一个新的值(value)。我无法在生产代码中更改 iValueMono 的实现方式(例如,使其有状态来存储值)。我怎样才能实现这个,以便值(value)提供者只被调用一次,我就得到最终结果“X11”?

当然,我对非阻塞、响应式(Reactive)的方式感兴趣。

最佳答案

使用Mono.cache()答案是:

Turn this Mono into a hot source and cache last emitted signals for further Subscriber.

使用它:

Mono<String> iValueMono = Mono.fromSupplier(() -> {
int iValue = iCounter.getAndIncrement();
System.out.println("iValueMono CALL: " + iValue);
return String.valueOf(iValue);
}).cache();

只需调用供应商一次即可达到预期结果。

关于java - Spring Reactive - 重用Mono值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com