Usecase of lazily evaluated properties


(Crazyjavahacking) #1

Hi,

in the documentation there is the notion of Mapping extension properties to task properties, but it only shows statically evaluated String value.

I wrote example with lazy evaluation and want to hear if there i anything that can be improved in he following code. Thanks!

apply plugin: PropertyUsecasePlugin

class PropertyUsecasePlugin implements Plugin<Project> {
    void apply(Project project) {
        def extension = project.extensions.create('propertyUsecase', PropertyUsecaseExtension, project)

        project.tasks.create('useCase', UsecaseTask) {
            message    = extension.message
            systemProp = extension.systemProp
        }
    }
}

class PropertyUsecaseExtension {
    final PropertyState<String> message
    final PropertyState<String> systemProp

    PropertyUsecaseExtension(Project project) {
        message    = project.property(String)
        systemProp = project.property(String)

        message.set('default message value')
        systemProp.set('default system prop')
    }

    void setMessage(Provider<String> message) {
        this.message.set(message)
    }

    void setSystemProp(Provider<String> systemProp) {
        this.systemProp.set(systemProp)
    }
}

class UsecaseTask extends DefaultTask {
    final PropertyState<String> message    = project.property(String)
    final PropertyState<String> systemProp = project.property(String)

    void setMessage(PropertyState<String> message) {
        this.message.set(message)
    }

    void setSystemProp(PropertyState<String> systemProp) {
        this.systemProp.set(systemProp)
    }

    @TaskAction
    void printMessage() {
        println message   .get()
        println systemProp.get()
    }
}

def value = 1
System.setProperty('lala', '123')

propertyUsecase {
    message    = provider { println "Calling closure"; 'trala' + value }
    systemProp = provider { System.getProperty('lala') }
}

value = 2
System.setProperty('lala', '456')