java - 为什么 StepVerifer 虚拟时间不适用于 Flux?

标签 java project-reactor

我一直在使用 lite-rx-api-hands-on尝试了解 Reactor 的教程,我对其中一项测试的结果有点困惑,尝试使用 StepVerifier 进行虚拟时间。

这非常有效:

@Test
public void expect10Elements() {
    StepVerifier.withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(10))
                .thenAwait(Duration.ofSeconds(10))
                .expectNextCount(10)
                .expectComplete()
                .verify();
}

但这行不通

@Test
public void expect10Elements() {
    Flux<Long> flux = Flux.interval(Duration.ofSeconds(1)).take(10);

    StepVerifier.withVirtualTime(() -> flux)
                .thenAwait(Duration.ofSeconds(10))
                .expectNextCount(10)
                .expectComplete()
                .verify();
}

如果我在发布者中发布之前没有订阅通量,我不太明白为什么会发生这种情况。有人可以帮忙吗?

最佳答案

这是因为虚拟时间的实现方式。

有关解释,请参阅Reactor Reference :

This virtual time feature plugs in a custom Scheduler in Reactor’s Schedulers factory. Since these timed operators usually use the default Schedulers.parallel() scheduler, replacing it with a VirtualTimeScheduler does the trick. However, an important prerequisite is that the operator be instantiated after the virtual time scheduler has been activated.

To increase the chances that this happens correctly, the StepVerifier does not take a simple Flux as input. withVirtualTime takes a Supplier, which guides you into lazily creating the instance of the tested flux after having done the scheduler set up.

Take extra care to ensure the Supplier<Publisher<T>> can be used in a lazy fashion. Otherwise, virtual time is not guaranteed. Especially avoid instantiating the Flux earlier in the test code and having the Supplier return that variable. Instead, always instantiate the Flux inside the lambda.

关于java - 为什么 StepVerifer 虚拟时间不适用于 Flux?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60576916/

相关文章:

java - 类型转换泛型类

java - 如何在项目 react 器中组合来自两个 react 流的数据?

java - WebFlux 链接调用多个服务和响应聚合

java - 当响应不包含媒体类型 header 时,Spring WebClient 抛出 "Only one connection receive subscriber allowed"

java - 检查字符串中是否有给定的字母表

java - 在 Java 中读取 Microsoft Access 文件

java - 使用 Spring Data R2DBC 查找/修改/保存或更新插入

java - Spring 网络客户端: retry with backoff on specific error

java - Netty - 其他握手管道?

java - 是否可以查看 API 类的源代码?