迭代异步函数

时间:2018-01-15 14:38:06

标签: asynchronous java-8 vert.x

使用Twitch APIvert.x - 我希望使用WebClient和Twitch' s {{1}继续向Twitch的API发送请求响应逐页。但是,由于vert.x的异步性,我不确定如何返回并继续进行查询,直到满足条件。

到目前为止我的代码

cursor

理想情况下,我可以使用上一个请求中的public void getEntireStreamList(Handler<AsyncResult<JsonObject>> handler) { JsonObject data = new JsonObject(); getLiveChannels(100, result -> { if(result.succeeded()) { JsonObject json = result.result(); String cursor = json.getJsonObject("pagination").getString("cursor"); data.put("data", json.getJsonArray("data")); if(json.getJsonArray("data").size() < 100) { // IF NOT LAST PAGE // GO BACK AND DO AGAIN WITH CURSOR IN REQUEST } handler.handle(Future.succeededFuture(data)); } else handler.handle(Future.failedFuture(result.cause())); }); } 字符串调用getLiveChannels以继续搜索。

1 个答案:

答案 0 :(得分:1)

您需要使用Future组合。

这是我的问题代码:

public void getEntireStreamList(Handler<AsyncResult<JsonObject>> handler) {
    JsonArray data = new JsonArray();
    // create initial Future for first function call
    Future<JsonObject> initFuture = Future.future();

    // complete Future when getLiveChannels completes
    // fail on exception
    getLiveChannels(100, initFuture.completer());

    // Create a callback that returns a Future
    // for composition.
    final AtomicReference<Function<JsonObject, Future<JsonObject>>> callback = new AtomicReference<>();
    // Create Function that calls composition with itself.
    // This is similar to recursion.
    Function<JsonObject, Future<JsonObject>> cb = new Function<JsonObject, Future<JsonObject>>() {
        @Override
        public Future<JsonObject> apply(JsonObject json) {
            // new Future to return
            Future<JsonObject> f = Future.future();
            // Do what you wanna do with the data
            String cursor = json.getJsonObject("pagination").getString("cursor");
            data.addAll(json.getJsonArray("data"));
            // IF NOT LAST PAGE
            if(json.getJsonArray("data").size() == 100) {
                // get more live channels with cursor
                getLiveChannels(100, cursor, f.completer());
                // return composed Future
                return f.compose(this);
            }
            // Otherwise return completed Future with results.
            f.complete(new JsonObject().put("data", data));
            return f;
        }
    };

    Future<JsonObject> composite = initFuture.compose(cb);
    // Set handler on composite Future (ALL composed futures together)
    composite.setHandler(result -> handler.handle(result));
}

如果您阅读sequential Future composition上的Vert.x文档,则代码+注释应该说明一切。