How to create a Mono from a completableFuture

被刻印的时光 ゝ 提交于 2020-01-15 12:18:07

问题


I am trying to wrap CompletableFuture inside a Reactor Mono type in order to simplify my transform operations. Project Reactor is more convenient in general! I am working inside an AWS Lambda function and I am invoking AWS services such as S3, SQS, etc... using the new AWS Java SDK 2.x version. This new SDK allows to make asynchronous calls to AWS services and returns CompleteableFuture objects.

For example:

S3AsyncClient s3AsyncClient = S3AsyncClient.builder().build();    
Mono.fromFuture(s3AsyncClient.getObject(b -> 
b.bucket(bucketId).key(objectKey), AsyncResponseTransformer.toBytes()).subscribe()
System.out.println("stuff");

The problem is, when my main code invokes the CompletableFuture (s3AsyncClient.getObject), suddenly the execution thread switches to the CompleteableFuture thread and my main method that invoked the Mono returns before the CompletableFuture completes.

Basically, from the example above, the "stuff" string gets printed before the s3AsyncClient.getObject completes.

How can I make sure the Mono and the CompletableFuture executes within the same thread or how do I make sure my lambda doesn't terminate before the CompletableFuture have completed?

For those wondering, I only get this behavior when I deploy my code remotely to AWS Lambda. I don't experience this behavior locally...


回答1:


//.thenApply will wait for your future to complete first and then return Mono<T> Mono.fromFuture(yourCompletableFuture.thenApply(x -> x.doSomething);



来源:https://stackoverflow.com/questions/54154979/how-to-create-a-mono-from-a-completablefuture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!