Asynchronous 使用异步函数迭代
使用andAsynchronous 使用异步函数迭代,asynchronous,java-8,vert.x,Asynchronous,Java 8,Vert.x,使用andvert.x——我希望通过WebClient和Twitch的光标响应一页一页地连续向Twitch的API发送请求。但是,由于vert.x的异步特性,我不知道如何返回并继续执行查询,直到满足条件为止 这是到目前为止我的代码 public void getEntireStreamList(Handler<AsyncResult<JsonObject>> handler) { JsonObject data = new JsonObject(); g
vert.x
——我希望通过WebClient
和Twitch的光标
响应一页一页地连续向Twitch的API发送请求。但是,由于vert.x的异步特性,我不知道如何返回并继续执行查询,直到满足条件为止
这是到目前为止我的代码
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()));
});
}
public void getEntireStreamList(处理程序){
JsonObject数据=新的JsonObject();
GetLiveChannel(100,结果->{
if(result.successed()){
JsonObject json=result.result();
字符串游标=json.getJsonObject(“分页”).getString(“游标”);
data.put(“data”,json.getJsonArray(“data”);
if(json.getJsonArray(“data”).size()<100){//if不是最后一页
//返回并在请求中再次使用光标
}
handler.handle(Future.succeededFuture(data));
}否则
handler.handle(Future.failedFuture(result.cause());
});
}
理想情况下,我可以使用上一个请求中的
光标字符串调用getLiveChannels
,以继续搜索。您需要使用将来的合成
以下是我针对您的问题的代码:
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));
}
public void getEntityStreamList(处理程序)