Skip to main content

Kotlin Multiplatform SDK Reference

Star on GitHub Kotlin CI Maven Central Snapshot Quality Gate Status SonarCloud Coverage

Getting started

1. Install the ConfigCat SDK

val configcat_version: String by project

kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.configcat:configcat-kotlin-client:$configcat_version")
}
}
}
}

2. Import the ConfigCat SDK

import com.configcat.*

3. Create the ConfigCat client with your SDK Key

import com.configcat.*

suspend fun main() {
val client = ConfigCatClient("#YOUR-SDK-KEY#")
}

4. Get your setting value

import com.configcat.*

suspend fun main() {
val client = ConfigCatClient("#YOUR-SDK-KEY#")
val isMyAwesomeFeatureEnabled = client.getValue("isMyAwesomeFeatureEnabled", false)
if (isMyAwesomeFeatureEnabled) {
doTheNewThing()
} else {
doTheOldThing()
}
}

5. Close the client on application exit

You can safely shut down all clients at once or individually and release all associated resources on application exit.

ConfigCatClient.close() // closes all clients

ConfigCatClient.close(client) // closes a specific client

Configuring the ConfigCat Client

ConfigCat Client is responsible for:

  • managing the communication between your application and ConfigCat servers.
  • caching your setting values and feature flags.
  • serving values quickly in a failsafe way.

ConfigCatClient(<sdkKey>) returns a client with default options.

PropertiesDescription
dataGovernanceOptional, defaults to DataGovernance.GLOBAL. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: DataGovernance.GLOBAL, DataGovernance.EU_ONLY.
baseUrlOptional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations.
requestTimeoutMsOptional, defaults to 30s. Sets the underlying HTTP client's request timeout. More about HTTP Timeout.
configCacheOptional, sets a custom cache implementation for the client. More about cache.
pollingModeOptional, sets the polling mode for the client. More about polling modes.
loggerOptional, sets the internal logger. More about logging.
logLevelOptional, defaults to LogLevel.WARNING. Sets the internal log level. More about logging.
flagOverridesOptional, configures local feature flag & setting overrides. More about feature flag overrides.
httpEngineOptional, configures the underlying Ktor HTTP engine. More about HTTP engines.
httpProxyOptional, configures HTTP proxy for the underlying Ktor HTTP engine. More about HTTP proxy.
val client = ConfigCatClient("#YOUR-SDK-KEY#") {
pollingMode = autoPoll()
logLevel = LogLevel.INFO
requestTimeoutMs = 10_000
}
caution

We strongly recommend you to use the ConfigCatClient as a Singleton object in your application. The ConfigCatClient(<sdkKey>) factory method gets or constructs singleton client instances for your SDK keys. These clients can be closed all at once or individually with the ConfigCatClient.close() method.

Anatomy of getValue()

ParametersDescription
keyREQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
val value = client.getValue(
key = "keyOfMySetting",
defaultValue = false,
user = ConfigCatUser("#USER-IDENTIFIER#"), // Optional User Object
)

User Object

The User Object is essential if you'd like to use ConfigCat's Targeting feature.

val user = ConfigCatUser(identifier = "435170f4-8a8b-4b67-a723-505ac7cdea92")  
val user = ConfigCatUser(identifier = "[email protected]")   

Customized user object creation:

ArgumentDescription
identifierREQUIRED. Unique identifier of a user in your application. Can be any value, even an email address.
emailOptional parameter for easier targeting rule definitions.
countryOptional parameter for easier targeting rule definitions.
customOptional map for custom attributes of a user for advanced targeting rule definitions. e.g. User role, Subscription type.
val user = ConfigCatUser(
identifier = "435170f4-8a8b-4b67-a723-505ac7cdea92",
email = "[email protected]",
country = "United Kingdom",
custom = mapOf(
"SubscriptionType" to "Pro",
"UserRole" to "Admin"
)
)

Polling Modes

The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the internal cache then all getValue() calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.
More about polling modes.

Auto polling (default)

The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.

Use the the pollingIntervalSeconds option parameter of the autoPoll() to change the polling interval.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
pollingMode = autoPoll {
pollingIntervalSeconds = 100
}
}

Adding a callback to onConfigChanged option parameter will get you notified about changes.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
pollingMode = autoPoll {
pollingIntervalSeconds = 100
onConfigChanged = {
// here you can subscribe to configuration changes
}
}
}

Available options:

Option ParameterDescriptionDefault
pollingIntervalSecondsPolling interval.60
maxInitWaitTimeSecondsMaximum waiting time between the client initialization and the first config acquisition in seconds.5
onConfigChangedCallback to get notified about changes.-

Lazy loading

When calling getValue() the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case the getValue() will return the setting value after the cache is updated.

Use the cacheRefreshIntervalSeconds option parameter of the lazyLoad() to set cache lifetime.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
pollingMode = lazyLoad {
cacheRefreshIntervalSeconds = 100
}
}

Available options:

ParameterDescriptionDefault
cacheRefreshIntervalSecondsCache TTL.60

Manual polling

Manual polling gives you full control over when the config.json (with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling refresh() is your application's responsibility.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
pollingMode = manualPoll()
}

client.refresh()

getValue() returns defaultValue if the cache is empty. Call refresh() to update the cache.

Flag Overrides

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

  • Local/Offline mode (OverrideBehavior.LOCAL_ONLY): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

  • Local over remote (OverrideBehavior.LOCAL_OVER_REMOTE): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

  • Remote over local (OverrideBehavior.REMOTE_OVER_LOCAL): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a Map<String, Any>.

val client = ConfigCatClient("localhost") {
flagOverrides = {
behavior = OverrideBehavior.LOCAL_ONLY
dataSource = OverrideDataSource.map(
mapOf(
"enabledFeature" to true,
"disabledFeature" to false,
"intSetting" to 5,
"doubleSetting" to 3.14,
"stringSetting" to "test"
)
)
}
}

getAllKeys()

You can query the keys of each feature flag and setting with the getAllKeys() method.

val client = ConfigCatClient("#YOUR-SDK-KEY#")
val keys = client.getAllKeys()

getAllValues()

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

val client = ConfigCatClient("#YOUR-SDK-KEY#")
val settingValues = client.getAllValues()

// invoke with user object
val user = ConfigCatUser(identifier = "435170f4-8a8b-4b67-a723-505ac7cdea92")
val settingValuesTargeting = client.getAllValues(user)

Custom Cache

You have the option to inject your custom cache implementation into the client. All you have to do is to implement the ConfigCache interface:

class MyCustomCache : ConfigCache {
override suspend fun read(key: String): String {
// here you have to return with the cached value
}

override suspend fun write(key: String, value: String) {
// here you have to store the new value in the cache
}
}

Then use your custom cache implementation:

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
configCache = MyCustomCache()
}

HTTP Engine

The ConfigCat SDK internally uses Ktor to download the latest configuration over HTTP. For each platform the SDK includes a specific HTTP engine:

  • Android / JVM: ktor-client-okhttp
  • macOS / iOS / tvOS / watchOS: ktor-client-darwin
  • JavaScript / Node.js: ktor-client-js
  • Windows / Linux: It is possible to use Ktor's Curl engine.

You can set/override the HTTP engine like the following:

// this example configures the SDK to use the Curl engine for HTTP communication.
import com.configcat.*
import io.ktor.client.engine.curl.*

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
httpEngine = Curl.create {
// additional engine configuration
}
}

HTTP Timeout

You can set the maximum wait time for a ConfigCat HTTP response.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") { 
requestTimeoutMs = 10_000
}

The default request timeout is 30 seconds.

HTTP Proxy

If your application runs behind a proxy you can do the following:

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") { 
httpProxy = ProxyBuilder.http("http://proxy-server:1234/")
}

You can check tha availability of the proxy configuration in specific HTTP engines here.

Force refresh

Any time you want to refresh the cached configuration with the latest one, you can call the refresh() method of the library, which initiates a new download and updates the local cache.

Logging

The default logger used by the SDK is simply using println() to log messages, but you can override it with your custom logger implementation via the logger client option. The custom implementation must satisfy the Logger interface.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
logger = MyCustomLogger()
}

You can change the verbosity of the logs by passing a logLevel parameter to the client options.

val client = ConfigCatClient("<PLACE-YOUR-SDK-KEY-HERE>") {
logLevel = LogLevel.INFO
}

Available log levels:

LevelDescription
OFFTurn the logging off.
ERROROnly error level events are logged.
WARNINGDefault. Errors and Warnings are logged.
INFOErrors, Warnings and feature flag evaluation is logged.
DEBUGAll of the above plus debug info is logged. Debug logs can be different for other SDKs.

Info level logging helps to inspect how a feature flag was evaluated:

2022-08-09 15:58:54 UTC [INFO]: ConfigCat - Evaluating 'isPOCFeatureEnabled'
User object: {Identifier: 435170f4-8a8b-4b67-a723-505ac7cdea92, Email: [email protected]}
Evaluating rule: [Email:[email protected]] [CONTAINS] [@something.com] => no match
Evaluating rule: [Email:[email protected]] [CONTAINS] [@example.com] => match, returning: true

Sample Apps

Check out our Sample Applications how they use the ConfigCat SDK

Look Under the Hood