Executing authorization queries concurrently
In the previous example, we saw how to use RxJava operators and the Rxified Vert.x API to execute asynchronous operations in order. But sometimes this guarantee is not required, or you simply want them to run concurrently for performance reasons.
The JWT token generation process in the HttpServerVerticle
is a good example of such a situation. To create a token, we need all authorization queries to complete, but queries are independent from each other:
auth.rxAuthenticate(creds).flatMap(user -> {
Single<Boolean> create = user.rxIsAuthorized("create"); (1)
Single<Boolean> delete = user.rxIsAuthorized("delete");
Single<Boolean> update = user.rxIsAuthorized("update");
return Single.zip(create, delete, update, (canCreate, canDelete, canUpdate) -> { (2)
return jwtAuth.generateToken(
new JsonObject()
.put("username", context.request().getHeader("login"))
.put("canCreate", canCreate)
.put("canDelete", canDelete)
.put("canUpdate", canUpdate),
new JWTOptions()
.setSubject("Wiki API")
.setIssuer("Vert.x"));
});
}).subscribe(token -> {
context.response().putHeader("Content-Type", "text/plain").end(token);
}, t -> context.fail(401));
Three
Single
objects are created, representing the different authorization queries.When the three operations complete successfully, the
zip
operator callback is invoked with the results.