如何将Vert.x Future.compose()转换为等效的RxJava2实现

时间:2018-04-21 14:45:52

标签: rx-java2 vert.x

我有一段代码如下:

this.initConfigRetriever()                // Produces Future<JsonObject>
    .compose(this::asyncLoadDbSchema)     // Consumes JsonObject, produces Future<Void>
    .compose(v -> this.provisionRouter()) // Produces Future<RouterFactory>
    .compose(this::createHttpServer)      // Consumes RouterFactory
    .compose(s -> startFuture.complete(), startFuture);

我想知道如何将其转换为RxJava2中的等效内容?理想情况下,我想要像Completable那样的东西,但是值从一个传递到下一个:

例如:

this.initConfigRetriever()            // Returns a JsonObject
    .andThen(this::asyncLoadDbSchema) // Consumes JsonObject and produces a Void
    .andThen(this::provisionRouter)   // Consume Void and produces RouterFactory
    .andThen(this::createHttpServer)  // Consumes RouterFactory
    .onError(startFuture::fail)       // Consumes any errors along the chain

2 个答案:

答案 0 :(得分:1)

下面的

可能与您正在寻找的内容相符。

  • flatMap运算符允许您将值从一个流传递到另一个流的创建
  • 错误可由订阅者处理
  • 我使用Single假设这似乎与运行一次的引导逻辑有关

    // Produces Future<JsonObject>
    Single.just("...")
            .flatMapCompletable {
                // Consumes JsonObject, emits "completion" (or ends the stream)
                Completable.fromCallable { /* ... */ }
            }
            .toSingle {
                // On complete produces RouterFactory
                Single.just("...")
            }
            .flatMapCompletable {
                // Consumes RouterFactory, emits "completion" (or ends the stream)
                Completable.fromCallable { /* ... */ }
            }
            .subscribeBy(
                    onComplete = { 
                        // Handle completion...
                    },
                    onError = { error -> 
                        // Handle errors... 
                    }
            )
    

我希望有所帮助!

答案 1 :(得分:0)

这是我的结构最终看起来像

this.initConfigRetriever()             // If it fails, jump to error handler
    .flatMap(this::asyncLoadDbSchema)  // If it fails, jump to error handler
    .flatMap(this::provisionRouter)    // If it fails, jump to error handler
    .flatMap(this::createHttpServer)   // If it fails, jump to error handler
    .doOnError(startFuture::fail)
    .subscribe(m -> startFuture.complete()); // If all steps succeeded

我实现这一点的方法是flatMapped的每个方法都返回Maybe<T>。这很干净地解决了我的问题。

一个有趣的消极方面是,当我进行调试以解决这个问题时,很难弄清楚出错的地方(我从未开始使用流)。为了使这在IntelliJ中更容易调试,我将方法引用转换为lambdas,以便我可以在lambdas中设置断点。

有关详细信息,您可以看到代码HERE