Async Argument
To parse arguments asynchronously you can choose from three different ways:
- Create
ArgumentResolverwith an asyncParseResult<T>(recommended) - Add
@Asyncannotation before argument - Use argument with the
CompletableFuture<T>type
1. Use async ParseResult<T> recommended
To create an argument resolver that parses arguments asynchronously, you need to:
- Return a
ParseResult.completableFuture()in theparse()method - Validate the argument synchronously in the
match()method
java
public class UserArgumentResolver extends ArgumentResolver<CommandSender, User> {
private final Pattern VALID_USER_PATTERN = Pattern.compile("^[a-zA-Z0-9_]{3,16}$");
private final UserService userService;
public UserArgumentResolver(UserService userService) {
this.userService = userService;
}
@Override
protected ParseResult<User> parse(Invocation<CommandSender> invocation, Argument<User> context, String argument) {
CompletableFuture<User> userFuture = userService.getUser(argument);
return ParseResult.completableFuture(userFutur, user -> {
if (user == null) {
return ParseResult.failure("User not found.");
}
return ParseResult.success(user);
});
}
@Override
public boolean match(Invocation<CommandSender> invocation, Argument<User> context, String argument) {
return VALID_USER_PATTERN.matcher(argument).matches();
}
}Full example
See this example on GitHub.
2. @Async annotation
You need to use the @Async annotation on the argument:
Java
@Command(name = "user")
public class UserCommand {
@Execute(name = "load")
void execute(@Async @Arg User argument) {
System.out.print("This message is triggered in the main thread!");
}
}WARNING
The @Async annotation on the argument will parse the argument asynchronously, but the command will be executed in the main thread.
3. CompletableFuture<T> type
Using CompletableFuture<T> is more complicated:
java
@Command(name = "user")
public class UserCommand {
@Execute(name = "load")
void execute(@Arg CompletableFuture<User> argument) {
System.out.print("This message is triggered in the main thread!");
argument.whenComplete((user, error) -> {
if (error != null) {
return;
}
System.out.print("This message is triggered asynchronously!");
});
}
}
Norbert Dejlich