简体   繁体   中英

Java slack sdk client how to make the call async

I'm trying to make a call by using slack's sdk client in java in order to get user's id by using the email name. The slack client returns CompletableFuture object. I can get the user_name if i use get() method but as far as i understand, it's a synchronous function and it will make the application slower. Is there another way to make this call asynchronous?

public static String lookUpUserId(String email) throws ExecutionException, InterruptedException {

       CompletableFuture<UsersLookupByEmailResponse> response = slackClient.usersLookupByEmail(r -> r
        .email(email));

       UsersLookupByEmailResponse data = response.get();

       return data.getUser().getId();
}

I tried using supplyFunc and thenApply like this but it gives an error saying 'missing return statement' although i return a value. I'm just concerned about the performance and curious if there's aa better way to handle this. Thanks

response.thenApply(r->r.getUser().getId());

Since the call returns CompletableFuture , it is alredy asynchronous. Yes, get () method is a synchronous function. Using it will NOT make the application slower, it will make application consume more memory. Asynchronous access like

   response.thenApply(r->r.getUser().getId());

looks correct.

The reason of error message is that the method lookUpUserId is declared as returning String and so must have a return staement. If you want to make it asynchronous, then declare it as returning CompletableFuture<String> and add return statement

 return response.thenApply(r->r.getUser().getId());

I don't know much specifically about the slack api but some information can be found in this answer with regards to housing your function in a class that implements Runnable .

Make your `CompletableFuture` in the constructor and run your gets in `run()`. 

In my opinion it is a best practice to process all of your api requests off of the main thread but you should know that running some single thing in a separate thread on one line and joining that thread back on the next is only going to add a little overhead without any performance advantages. If you are processing a batch of requests you should start each on independent threads with a for loop and join them all together after.


I'm also noticing that my referenced answer doesn't really cover thread joins for retrieving your results sooo you will probably also find this informative. And if you havn't learned about object oriented programming yet that's ok! you'll be writing your own classes in no time .

Edit: Ask for code if you need it, It's better if you write it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM