Skip to content

Hey there! If you like my work, you can support me by sponsoring me on GitHub. Thanks! ❤

Sponsor me
on GitHub

Async Argument

To parse arguments asynchronously you can choose from three different ways:

  1. Create ArgumentResolver with an async ParseResult<T> (recommended)
  2. Add @Async annotation before argument
  3. Use argument with the CompletableFuture<T> type

To create an argument resolver that parses arguments asynchronously, you need to:

  • Return a ParseResult.completableFuture() in the parse() 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!");
        });
    }
}

Made by LiteDevelopers and Contributors with ❤️