标签: reactive-programming

RxSwift 如何有条件地控制按钮何时发出点击?

我想阻止我的 UIButtons 发出 RX tap 事件,直到某些控制流表明它已准备就绪。如果控制流恢复为未准备好,我希望再次禁用按钮。控制序列是一个ReplaySubject并且总是有值

我试过了skipUntil,但这是一次性操作——一旦控制序列发出,它就不能回到禁用状态——所有按钮按下都会通过,忽略控制序列

除非其他流具有特定值,否则如何限制 UIButton 发送点击事件?

let enableButtons = configStatusInputSequence
.filter { (configured, ready) -> Bool in
    return configured && ready
}

for button in controlButtons{
    button.rx.tap
        .skipUntil(enableButtons)
        .bind(to: commandOutputSequence)
        .disposed(by: bag)
}
Run Code Online (Sandbox Code Playgroud)

reactive-programming control-flow ios swift rx-swift

6
推荐指数
1
解决办法
2821
查看次数

如何将 Mono<String> 转换为 Mono<MyObject>?

我正在编写一个简单的 get 方法来从 API URL 检索评论。API 将 json 数据作为字符串返回。返回Mono<Object>会引发错误。请在下面找到 HTTP 响应。

{
    "timestamp": "2019-02-05T11:25:33.510+0000",
    "path": "Some URL",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Content type 'text/plain;charset=utf-8' not supported for bodyType=java.lang.Object"
}
Run Code Online (Sandbox Code Playgroud)

我发现响应是一个字符串。所以返回Mono<String>工作正常。但我想Mono<MyObject>从 API 响应中返回。

我如何转换Mono<String>为Mono<MyObject>?除了How to get String from Mono<String> in react java之外,我在 google 上找不到任何解决方案。

以下是我的服务类:

@Service
public class DealerRaterService {
    WebClient client = WebClient.create();
    String reviewBaseUrl = "Some URL";

    public Mono<Object> getReviews(String pageId, String …
Run Code Online (Sandbox Code Playgroud)

spring webclient reactive-programming project-reactor spring-webflux

6
推荐指数
1
解决办法
5810
查看次数

如何在 Kotlin 中将 actor 定义为一个类

actorKotlin 协程库中有一个概念:

fun CoroutineScope.counterActor() = actor<CounterMsg> {
    var counter = 0 // actor state
    for (msg in channel) { // iterate over incoming messages
        when (msg) {
            is IncCounter -> counter++
            is GetCounter -> msg.response.complete(counter)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

文档说

一个简单的actor可以写成一个函数,但是一个具有复杂状态的actor更适合一个类。

什么是在 Kotlin 中定义为类的演员的好例子?

reactive-programming actor kotlin

6
推荐指数
1
解决办法
402
查看次数

Redirection inside reactive Spring Webflux REST controller

I'm creating simple controller server for spring reactive project. While setting redirection to another location, I have found an error when calling http://localhost:8080/:

There was an unexpected error (type=Internal Server Error, status=500).
ModelAttributeMethodArgumentResolver does not support multi-value reactive type wrapper: interface reactor.netty.http.server.HttpServerResponse
java.lang.IllegalStateException: ModelAttributeMethodArgumentResolver does not support multi-value reactive type wrapper: interface reactor.netty.http.server.HttpServerResponse
    at org.springframework.util.Assert.state(Assert.java:94)
    at org.springframework.web.reactive.result.method.annotation.ModelAttributeMethodArgumentResolver.resolveArgument(ModelAttributeMethodArgumentResolver.java:112)
    at org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:123)
    at org.springframework.web.reactive.result.method.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:190)
    at org.springframework.web.reactive.result.method.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:133)
    at org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter.lambda$handle$1(RequestMappingHandlerAdapter.java:200)
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)
...
Run Code Online (Sandbox Code Playgroud)

This is the controller code:

There was an unexpected error (type=Internal …
Run Code Online (Sandbox Code Playgroud)

java reactive-programming spring-restcontroller spring-webflux

6
推荐指数
2
解决办法
3648
查看次数

如何测试Spring WebClient何时重试?

我需要实现以下行为:

  • 发出 REST 发布请求
  • 如果响应返回状态为429 Too many requests,则最多重试 3 次,延迟 1 秒
  • 如果第三次重试失败或发生任何其他错误,请记录并向数据库写入内容
  • 如果请求成功(http status 200),记录一些信息

我想使用 Spring WebClient 来实现此目的,并提出了以下代码:

Mono<ClientResponse> response = webClient.post()
            .uri(URI.create("/myuri"))
            .body(BodyInserters.fromObject(request))
            .retrieve()
            .onStatus(httpStatus -> httpStatus.equals(HttpStatus.TOO_MANY_REQUESTS), 
                      response -> Mono.error(new TooManyRequestsException("System is overloaded")))
            .bodyToMono(ClientResponse.class)
            .retryWhen(Retry.anyOf(TooManyRequestsException.class)
                                          .fixedBackoff(Duration.ofSeconds(1)).retryMax(3))
            .doOnError(throwable -> saveToDB(some_id, throwable))
            .subscribe(response -> logResponse(some_id, response));
Run Code Online (Sandbox Code Playgroud)

现在我想测试重试机制和错误处理是否按我的预期工作。也许我可以使用StepVerifier来达到此目的,但我只是不知道如何在我的情况下使用它。有什么有用的提示吗?

reactive-programming rx-java project-reactor spring-webclient

6
推荐指数
1
解决办法
1万
查看次数

Mono.toFuture() 是阻塞的吗?

从Mono#block() 的官方文档中可以看出:

订阅此 Mono 并无限期阻塞,直到收到下一个信号。返回该值,如果 Mono 完成为空,则返回 null。如果 Mono 出错,则会抛出原始异常(如果是受检查的异常,则将其包装在 RuntimeException 中)。

因此可以肯定 block() 方法是阻塞的,并且在解决之前它不会执行下一行block()。

但我的困惑是,当我使用时,toFuture()期望它是非阻塞的,但它的行为与block方法完全相同。在Mono#toFuture() 的文档中指出:

将此 Mono 转换为 CompletableFuture 在 onNext 或 onComplete 上完成并在 onError 上失败。

单声道#toFuture()

不太清楚。本文档中没有任何地方说Mono#toFuture()阻塞。

  1. 请确认我的toFuture()方法是阻塞还是非阻塞?
  2. 另外,如果它是非阻塞的,那么哪个线程将负责执行里面的代码CompletableFuture?

更新:添加了代码片段

使用Mono.block()方法:

    long time = System.currentTimeMillis();
    String block = Mono.fromCallable(() -> {
        logger.debug("inside in fromCallable() block()");
        //Upstream httpcall with apache httpClient().
        // which takes atleast 1sec …
Run Code Online (Sandbox Code Playgroud)

java reactor reactive-programming apache-commons-httpclient

6
推荐指数
2
解决办法
9759
查看次数

block()/blockFirst()/blockLast() 是阻塞的,在线程reactor-http-server-epoll-18中不支持

我正在尝试使用 WebTestClient 发布数据但不幸的是抛出了这样的消息:

java.lang.AssertionError: Status expected:<200> but was:<500>

> POST http://localhost:41087/movie
> Accept: [application/json;charset=UTF-8]
> WebTestClient-Request-Id: [1]
> Content-Type: [application/json;charset=UTF-8]
> Content-Length: [101]

{"movieId":1,"title":"Title for movie 1","genre":"Genre for movie 1","address":"Address for movie 1"}

< 500 INTERNAL_SERVER_ERROR Internal Server Error
< Content-Type: [application/json;charset=UTF-8]
< Content-Length: [226]

{"timestamp":"2020-01-03T10:02:18.467+0000","path":"/movie","status":500,"error":"Internal Server Error","message":"block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-server-epoll-18"}


    at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:200)
    at org.springframework.test.web.reactive.server.StatusAssertions.isEqualTo(StatusAssertions.java:59)
    at org.springframework.test.web.reactive.server.StatusAssertions.isEqualTo(StatusAssertions.java:51)
    at com.geborskimateusz.microservices.core.movie.MovieServiceApplicationTests.postAndVerify(MovieServiceApplicationTests.java:111)
    at com.geborskimateusz.microservices.core.movie.MovieServiceApplicationTests.getMovieNotFound(MovieServiceApplicationTests.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:515)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115) …
Run Code Online (Sandbox Code Playgroud)

spring reactive-programming spring-boot spring-webflux

6
推荐指数
1
解决办法
5467
查看次数

doOnNext() 不会被调用 Spring Webflux

我是反应式编程和 Spring Webflux 的新手,我有一种方法可以从 Redis 获取一些密钥,如果该密钥为 null 或不等于指定的字符串,我想抛出异常,但嵌套的 donOnNext 方法不会被调用并被customerRepository.save(customer)触发,而必须抛出异常并打破链条。有人可以向我解释一下 Reactor API 在我的例子中是如何表现的吗?

这是我的方法:

@Override
public Mono<RegistrationVerificationResDTO> verifyCustomerAndGenerateToken(Mono<VerifyOtpReqDTO> verifyOtpReqDTO) {
    return verifyOtpReqDTO
            .doOnNext(verifyDTO -> reactiveRedisOperations
                    .opsForValue()
                    .get(RedisDictionary.OTP_KEY + verifyDTO.getPhoneNumber())
                    .filter(otp -> otp.equalsIgnoreCase(verifyDTO.getOtp()))
                    .switchIfEmpty(Mono.error(ForbiddenException::new)))
            .map(verifyDTO -> customerRepository.findById(verifyDTO.getId())
                    .orElseThrow(() -> new NotFoundException("Customer not found")))
            .doOnNext(customer -> {
                customer.setVerified(true);
                customerRepository.save(customer);
            })
            .map(customer -> new RegistrationVerificationResDTO().setAccessToken("accessToken")
                    .setRefreshToken("refreshToken")
                    .setCustomer(customer));
}
Run Code Online (Sandbox Code Playgroud)

更新:我意识到如果我们在 doOnNext 方法中创建另一个发布者,因为 spring 仅订阅最外层的发布者,内部发布者不会被触发我已经更新了我的代码,但它仍然不起作用。

java reactive-programming spring-boot project-reactor spring-webflux

6
推荐指数
1
解决办法
5712
查看次数

无阻塞地通量到 List&lt;Objects&gt;

寻找将 Flux 转换为List<Object>. 如果我使用 block() 会出现错误。因此,需要在不阻塞呼叫的情况下进行通话。

Flux.from(Collection.find())
Run Code Online (Sandbox Code Playgroud)

使用反应式编程,但 graphql 期望List<objects>返回 Flux 并出错。

使用 Block() 编写代码

public List<Test> findAll() {
        return Flux.from(testCollection.find()).collectList().block();

}
Run Code Online (Sandbox Code Playgroud)

错误 :-

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-kqueue-7
Run Code Online (Sandbox Code Playgroud)

在这里,我需要返回,因为由于某种原因List<Test>我无法发送。Flux<Test>

java reactive-programming project-reactor graphql-java

6
推荐指数
1
解决办法
2万
查看次数

如何将 Flux&lt;Object&gt; 列表转换为 List&lt;Object&gt;

我有一个 Flux,我想将其转换为 List。我怎样才能做到这一点?

Flux<Object> getInstances(String serviceId); // Current one 
List<Object> getInstances(String serviceId); // Demanded one
Run Code Online (Sandbox Code Playgroud)

Java 8 或反应式组件有一个准备好的方法将其映射或转换为 List ??

我应该使用.map()

final List<ServiceInstance> sis = convertedStringList.parallelStream()
            .map( this.reactiveDiscoveryClient::getInstances )
            // It should be converted to List<Object>
Run Code Online (Sandbox Code Playgroud)

reactive-programming java-8 java-stream project-reactor reactive

6
推荐指数
1
解决办法
9273
查看次数