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:

  1. auth.rxAuthenticate(creds).flatMap(user -> {
  2. Single<Boolean> create = user.rxIsAuthorized("create"); (1)
  3. Single<Boolean> delete = user.rxIsAuthorized("delete");
  4. Single<Boolean> update = user.rxIsAuthorized("update");
  5. return Single.zip(create, delete, update, (canCreate, canDelete, canUpdate) -> { (2)
  6. return jwtAuth.generateToken(
  7. new JsonObject()
  8. .put("username", context.request().getHeader("login"))
  9. .put("canCreate", canCreate)
  10. .put("canDelete", canDelete)
  11. .put("canUpdate", canUpdate),
  12. new JWTOptions()
  13. .setSubject("Wiki API")
  14. .setIssuer("Vert.x"));
  15. });
  16. }).subscribe(token -> {
  17. context.response().putHeader("Content-Type", "text/plain").end(token);
  18. }, t -> context.fail(401));
  1. Three Single objects are created, representing the different authorization queries.

  2. When the three operations complete successfully, the zip operator callback is invoked with the results.