Skip to main content
Version: Config V1 (legacy)

Kotlin Multiplatform SDK Reference

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

info

This documentation applies to the v2.x version of the ConfigCat Kotlin Multiplatform SDK. For the documentation of the latest release, please refer to this page.

Getting started

1. Install the ConfigCat SDK

build.bradle.kts
val configcatVersion: String by project

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

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.closeAll() // closes all clients

client.close() // closes a specific client

Setting up 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.

Customizing the ConfigCat Client

To customize the SDK's behavior, you can pass an additional ConfigCatOptions.() -> Unit parameter to the ConfigCatClient() method where the ConfigCatOptions class is used to set up the ConfigCat Client.

import com.configcat.*
import kotlin.time.Duration.Companion.seconds

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
pollingMode = autoPoll()
logLevel = LogLevel.INFO
requestTimeout = 10.seconds
}

These are the available options on the ConfigCatOptions class:

PropertiesTypeDescription
dataGovernanceDataGovernanceOptional, 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.
baseUrlStringOptional, sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON.
requestTimeoutDurationOptional, defaults to 30s. Sets the underlying HTTP client's request timeout. More about HTTP Timeout.
configCacheConfigCacheOptional, sets a custom cache implementation for the client. More about cache.
pollingModePollingModeOptional, sets the polling mode for the client. More about polling modes.
loggerLoggerOptional, sets the internal logger. More about logging.
logLevelLogLevelOptional, defaults to LogLevel.WARNING. Sets the internal log level. More about logging.
flagOverrides(FlagOverrides.() -> Unit)?Optional, sets the local feature flag & setting overrides. More about feature flag overrides.
httpEngineHttpClientEngine?Optional, sets the underlying Ktor HTTP engine. More about HTTP engines.
httpProxyProxyConfig?Optional, sets up the HTTP proxy for the underlying Ktor HTTP engine. More about HTTP proxy.
defaultUserConfigCatUser?Optional, sets the default user. More about default user.
offlineBoolOptional, defaults to false. Indicates whether the SDK should be initialized in offline mode. More about offline mode.
hooksHooksOptional, used to subscribe events that the SDK sends in specific scenarios. More about hooks.
caution

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

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(identifier = "#USER-IDENTIFIER#"), // Optional User Object
)

Anatomy of getValueDetails()

getValueDetails() is similar to getValue() but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

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 details = client.getValueDetails(
key = "keyOfMySetting",
defaultValue = false,
user = ConfigCatUser(identifier = "#USER-IDENTIFIER#"), // Optional User Object
)

The details result contains the following information:

FieldTypeDescription
valueBoolean / String / Int / DoubleThe evaluated value of the feature flag or setting.
keyStringThe key of the evaluated feature flag or setting.
isDefaultValueBooleanTrue when the default value passed to getValueDetails() is returned due to an error.
errorString?In case of an error, this field contains the error message.
userConfigCatUser?The User Object that was used for evaluation.
matchedEvaluationPercentageRulePercentageRule?If the evaluation was based on a percentage rule, this field contains that specific rule.
matchedEvaluationRuleRolloutRule?If the evaluation was based on a Targeting Rule, this field contains that specific rule.
fetchTimeUnixMillisecondsLongThe last download time of the current config in unix milliseconds format.

User Object

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

val user = ConfigCatUser(identifier = "#UNIQUE-USER-IDENTIFIER#")
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 = "#UNIQUE-USER-IDENTIFIER#",
email = "[email protected]",
country = "United Kingdom",
custom = mapOf(
"SubscriptionType" to "Pro",
"UserRole" to "Admin"
)
)

Default user

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object either on SDK initialization:

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
defaultUser = ConfigCatUser(identifier = "[email protected]")
}

or with the setDefaultUser() method of the ConfigCat client.

client.setDefaultUser(ConfigCatUser(identifier = "[email protected]"))

Whenever the getValue(), getValueDetails(), or getAllValues() methods are called without an explicit user parameter, the SDK will automatically use the default user as a User Object.

val user = ConfigCatUser(identifier = "[email protected]")
client.setDefaultUser(user)

// The default user will be used at the evaluation process.
val value = client.getValue("keyOfMySetting", false)

When the user parameter is specified on the requesting method, it takes precedence over the default user.

val user = ConfigCatUser(identifier = "[email protected]")
client.setDefaultUser(user)

val otherUser = ConfigCatUser(identifier = "[email protected]")

// otherUser will be used at the evaluation process.
val value = await client.getValue("keyOfMySetting", false, otherUser)

For deleting the default user, you can do the following:

client.clearDefaultUser()

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 pollingInterval option parameter of the autoPoll() to change the polling interval.

import com.configcat.*
import kotlin.time.Duration.Companion.seconds

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
pollingMode = autoPoll {
pollingInterval = 100.seconds
}
}

Available options:

Option ParameterDescriptionDefault
pollingIntervalPolling interval.60.seconds
maxInitWaitTimeMaximum waiting time between the client initialization and the first config acquisition in seconds.5.seconds

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 getValue() will return the setting value after the cache is updated.

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

import com.configcat.*
import kotlin.time.Duration.Companion.seconds

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
pollingMode = lazyLoad {
cacheRefreshInterval = 100.seconds
}
}

Available options:

ParameterDescriptionDefault
cacheRefreshIntervalCache TTL.60.seconds

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 forceRefresh() is your application's responsibility.

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
pollingMode = manualPoll()
}

client.forceRefresh()

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

Hooks

With the following hooks you can subscribe to particular events fired by the SDK:

  • onClientReady(): This event is sent when the SDK reaches the ready state. If the SDK is initialized with lazy load or manual polling it's considered ready right after instantiation. If it's using auto polling, the ready state is reached when the SDK has a valid config JSON loaded into memory either from cache or from HTTP. If the config couldn't be loaded neither from cache nor from HTTP the onClientReady event fires when the auto polling's maxInitWaitTime is reached.

  • onConfigChanged(Map<String, Setting>): This event is sent when the SDK loads a valid config JSON into memory from cache, and each subsequent time when the loaded config JSON changes via HTTP.

  • onFlagEvaluated(EvaluationDetails): This event is sent each time when the SDK evaluates a feature flag or setting. The event sends the same evaluation details that you would get from getValueDetails().

  • onError(String): This event is sent when an error occurs within the ConfigCat SDK.

You can subscribe to these events either on SDK initialization:

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
hooks.addOnFlagEvaluated { details ->
/* handle the event */
}
}

or with the hooks property of the ConfigCat client:

client.hooks.addOnFlagEvaluated { details ->
/* handle the event */
}

Online / Offline mode

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

client.setOffline()

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

client.setOnline()

With client.isOffline you can check whether the SDK is in offline mode.

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 only (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.

Map

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"
)
)
}
}

Settings

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

val client = ConfigCatClient("localhost") {
flagOverrides = {
behavior = OverrideBehavior.LOCAL_ONLY
dataSource = OverrideDataSource.settings(
mapOf(
"noRuleOverride" to Setting("noRule", 1, emptyList(), emptyList(), "myVariationId"),
"ruleOverride" to Setting(
"noMatch",
1,
emptyList(),
listOf(
RolloutRule("ruleMatch", "Identifier", 2, "@example", "ruleVariationId")
),
"myVariationId"
),
"percentageOverride" to Setting(
"noMatch",
1,
listOf(
PercentageRule("A", 75.0, "percentageAVariationID"),
PercentageRule("B", 25.0, "percentageAVariationID")
),
emptyList(),
"myVariationId"
)
)
)
}
}

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 = "#UNIQUE-USER-IDENTIFIER#")
val settingValuesTargeting = client.getAllValues(user)

Cache

The SDK uses platform specific caching to store the downloaded config JSON.
These are the storage locations by platform:

  • Android: SharedPreferences. It has a dependency on android.content.Context, so it won't be enabled by default, but it can be explicitly set by providing an appropriate Context. (Here is an example)
  • iOS / macOS / tvOS / watchOS: NSUserDefaults.
  • JS (browser only): Browser localStorage.
  • On other platforms the SDK uses a memory-only cache.

If you want to turn off the default behavior, you can set the SDK's cache to null or to your own cache implementation.

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
configCache = null
}

Custom Cache

The ConfigCat SDK stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. If you prefer to use your own cache solution, such as an external or distributed cache in your system, you can implement the ConfigCache interface and set the configCache parameter in the setup callback of ConfigCatClient. This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure.

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("#YOUR-SDK-KEY#") {
configCache = MyCustomCache()
}
info

The Kotlin SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.

HTTP Engine

The ConfigCat SDK internally uses Ktor to download the latest config JSON 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 sets up the SDK to use the Curl engine for HTTP communication.
import com.configcat.*
import io.ktor.client.engine.curl.*

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
httpEngine = Curl.create {
// additional engine setup
}
}

HTTP Timeout

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

import com.configcat.*
import kotlin.time.Duration.Companion.seconds

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
requestTimeout = 10.seconds
}

The default request timeout is 30 seconds.

HTTP Proxy

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

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

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

Force refresh

Call the forceRefresh() method on the client to download the latest config JSON and update the 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.

class MyCustomLogger: Logger {
override fun error(message: String) {
// write the error logs
}

override fun error(message: String, throwable: Throwable) {
// write the error logs
}

override fun warning(message: String) {
// write the warning logs
}

override fun info(message: String) {
// write the info logs
}

override fun debug(message: String) {
// write the debug logs
}
}

Then you can use your custom logger implementation at the SDK's initialization:

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
logger = MyCustomLogger()
}

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

val client = ConfigCatClient("#YOUR-SDK-KEY#") {
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 - [5000] 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

Sensitive information handling

The frontend/mobile SDKs are running in your users' browsers/devices. The SDK is downloading a config JSON file from ConfigCat's CDN servers. The URL path for this config JSON file contains your SDK key, so the SDK key and the content of your config JSON file (feature flag keys, feature flag values, Targeting Rules, % rules) can be visible to your users. In ConfigCat, all SDK keys are read-only. They only allow downloading your config JSON files, but nobody can make any changes with them in your ConfigCat account.

If you do not want to expose the SDK key or the content of the config JSON file, we recommend using the SDK in your backend components only. You can always create a backend endpoint using the ConfigCat SDK that can evaluate feature flags for a specific user, and call that backend endpoint from your frontend/mobile applications.

Also, we recommend using confidential targeting comparators in the Targeting Rules of those feature flags that are used in the frontend/mobile SDKs.

Sample Apps

Check out our Sample Applications how they use the ConfigCat SDK

Look Under the Hood