Skip to content

Instant Commands

The banana man edited this page Feb 26, 2024 · 2 revisions

Instant Commands


The Problem

To make a command run when a button is pressed normally, you have to make a whole new class that extends Command and pass an instance of it as a parameter and all that yammer.

While that's great for long commands with many, many lines of code, that can end up with you having to sort through dozens of command class files to find the one you want. If only there was an easier way to pass all my short commands that only have to run like 6 lines!


INTRODUCING: INSTANT COMMANDS! (AS SEEN ON TV!!!!)

wowie
InstantCommands are just like commands, but instead of creating a class and passing an instance of that as the parameter, you can just pass a java Runnable instead! It's incredible!

You aren't convinced yet, are you?

Here's an example of a normal, stinky command:
ShooterCommand.java

...

private ShooterSubsystem shooter;

public ShooterCommand(ShooterSubsystem shooter)
{
    this.shooter = shooter;
}

@Override
public void initialize()
{
    shooter.doThingOne();
}

@Override
public void execute() 
{
    shooter.doThingTwo();
}

@Override
public void end()
{
    shooter.doThingThree();
    shooter.doThingFour();
}

...

Now that's a whole lot for something that only does three things!

Not only that, we just added one to the large, increasingly smelly pile of commands that we already have! The stench reminds me a lot of Renato.

The much better way is to use an InstantCommand under the edu.wpi.first.wpilibj2.command package. This uses Java Runnables rather than a command-extending class instance.

Here's an example of the AMAZING InstantCommand in effect!
RobotContainer.java

private void configureBindings()
{
    YButton
        .onTrue(new InstantCommand(() -> shooter.doThingOne()))
        .whileTrue(new InstantCommand(() -> shooter.doThingTwo()))
        .onFalse(new InstantCommand(() -> {
            shooter.doThingThree();
            shooter.doThingFour();
         }));
}

That's SO much better, isn't it?
However, there ARE cases where the boring, old normal Command-extending class should just be used over InstantCommand, such as if the command is really long and should probably be put in another file. InstantCommand should only really be used if the commands are small/insignificant.

Clone this wiki locally