Zerkz
Zerkz

Reputation: 721

Vertx3 - Return a value from a JDBC connection? (sql db).

I have an interface with a single method that returns "config" Object.

I want to utilize interface this in Android and Vertx3 environments.

Config retrieveConfig(String authCreds);

I'm trying to implement this in a vertx program, utilizing the JDBC client from it, but I'm running into issues.

jdbcClient.getConnection(sqlConnResult -> 
 //checks for success
 sqlConnResult.result().query(selectStatement, rows -> {
     //get result here, want to return it as answer to interface.
     //seems this is a "void" method in this scope.
});

Is this interface even possible with Vertx async code?

Upvotes: 2

Views: 1089

Answers (1)

Will
Will

Reputation: 6721

In Async programming you can't really return your value to the caller, because this would then be a blocking call - one of the main things async programming seeks to remove. This is why in Vertx a lot of methods return this or void.

Various paradigms exist as alternatives:

  • Vert.x makes extensive use of the Handler<T> interface where the handler(T result) method will be executed with the result.

  • Vert.x 3 also has support for the Rx Observable. This will allow you to return an Observable<T> which will emit the result to subscribers once the async task has completed.

  • Also, there is always an option to return Future<T> which, once the async task has completed will contain the result. Although Vert.x doesn't really use this very much.

So you're probably going to find it difficult to have a common interface like this for blocking and non-blocking api. Vertx offers nice and easy ways to run blocking code but I don't think that is a good solution in your case.

Personally, I would have a look at RxJava. There is support for Rx on Android, and has been well adopted in Vertx 3 - with almost every API call having a Rx equivalent.

Moving from:

Config retrieveConfig(String authCreds);

to

Observable<Config> retrieveConfig(String authCreds);

would give you the ability to have a common interface and for it to work on both Android & Vert.x. It would also give the added benefit of not having to stray into callback hell which Rx seeks to avoid.

Hope this helps,

Upvotes: 2

Related Questions