Gradle : Difference between doFirst() and doLast() methods

Point to Remember

  1. doFirst() and doLast() are the methods of org.gradle.api.Task interface.
  2. Both these methods take a Closure as a parameter.
  3. When a task is called this closure is called.

A Gradle task is sequence of Action objects and when a task is run all these actions are called in a sequence by calling Action.execute(T)

What are doFirst() and doLast() methods in a Gradle task.

doFirst(Closure action)

This method will add your closure as an action to the beginning of the action sequence. All the code that is written in this closure is executed first when the task is executed.

doLast(Closure action)

This method will add your closure as an action to the end of the action sequence. All the code in this closure is executed in last when the task is executed.

Let's take a look at the following example.

task A {
    doLast {
        println("Running task A :: LAST")
    }

    doFirst{
        println("Running task A :: FIRST ")
    }
}

When we run this task using command gradle -q A the following is the output of the command.

Running task A :: FIRST 
Running task A :: LAST

NOTE

Any code that is written outside these two methods will be executed every time, even if some other task is run.

For example, if we write our task in the following way and run

task A {
    println(" print statement 1")
    doLast {
        println("Running task A :: LAST")
    }
    println(" print statement 2")

    doFirst{
        println("Running task A :: FIRST ")
    }
    println(" print statement 3")
}

It will give the following output

 print statement 1
 print statement 2
 print statement 3
Running task A :: FIRST 
Running task A :: LAST

No comments :

Post a Comment