Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging multiple providers in Gradle. Difference between Provider.map vs project.provider

I have multiple Providers in Gradle and would want to merge those into a single Provider config object while keeping lazy configuration in mind.

What's the difference between using cascading Provider.flatMap & Provider.map, versus creating a new Provider with project.provider & using Provider.get()?

Given multiple Providers:

// build.gradle.kts

val envProvider: Provider<String> = project.provider {
    val env: String? by project
    env ?: "sit"
}

val accountProvider: Provider<String> = project.provider {
    val account: String by project
    account
}

val regionProvider: Provider<String> = project.provider {
    val region: String? by project
    region ?: "us-east-1"
}

Merging to a single Provider using Provider.flatMap and Provider.map:

val configProvider: Provider<Config> = envProvider.flatMap { env ->
    accountProvider.flatMap { account ->
        regionProvider.map { region ->
            Config(
                env = env,
                account = account,
                region = region
            )
        }
    }
}

Merging to a single Provider using project.provider and Provider.get:

val configProvider: Provider<Config> = project.provider {
    Config(
        env = envProvider.get(),
        account = accountProvider.get(),
        region = regionProvider.get()
    )
}

like image 755
Adrian Avatar asked Nov 14 '25 12:11

Adrian


1 Answers

From the docs for get():

Returns the value of this provider if it has a value present, otherwise throws {@code java.lang.IllegalStateException}.

From the docs for map() and flatMap():

The new provider will be live, so that each time it is queried, it queries this provider and applies the transformation to the result. Whenever this provider has no value, the new provider will also have no value and the transformation will not be called.

There are 2 differences using Provider.get() and Provider.map & Provider.flatMap

  • When you have no value present, calling get() will throw an exception whereas calling map() or flatMap() will just not run the transformation you give. (The lambda block). In your case, if any of envProvider, accountProvider or regionProvider does not have a value present when you call get, then you will get an exception. On the other hand, it will just not execute the lambda you give for the map or flatMap but you will still get a provider with no value inside.

  • map and flatMap returns a live Provider which means that even if the value is not present when you call, the transformation lambda you give to map or flatMap will be executed whenever there is a value present. With get, you only get an exception when there is no value.

like image 130
Fatih Avatar answered Nov 17 '25 10:11

Fatih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!