---
title: "Android SDK"
description: "Install and configure the Android SDK, evaluate configs and feature flags, and keep your UI current as values change"
canonical_url: "https://docs.configdirector.com/sdks/mobile/android"
---
# Android SDK

> Install and configure the Android SDK, evaluate configs and feature flags, and keep your UI current as values change

<div hidden="true" dataTitleIcon="android">



</div>

<external-badges package-url="/sdks/maven-repository" registry="maven" repo="android-sdk">



</external-badges>

## Introduction

The Android SDK is intended to be used by Android applications. It evaluates your configs against a context, keeps them current as they change in the dashboard, and hands your UI values it can re-render from.

It is written in Kotlin and is meant to be used from Kotlin and Java alike. Every API has a form that works without coroutines, and the Kotlin conveniences — `suspend` functions, `Flow`, and typed extensions — sit on top of it. It ships as three artifacts:

<table>
<thead>
  <tr>
    <th>
      Artifact
    </th>
    
    <th>
      Contents
    </th>
    
    <th>
      Minimum SDK
    </th>
    
    <th>
      Java bytecode
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        com.configdirector:android-sdk
      </code>
    </td>
    
    <td>
      The SDK
    </td>
    
    <td>
      21
    </td>
    
    <td>
      8
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        com.configdirector:android-sdk-compose
      </code>
    </td>
    
    <td>
      Optional Jetpack Compose bindings
    </td>
    
    <td>
      21
    </td>
    
    <td>
      11
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        com.configdirector:android-sdk-testing
      </code>
    </td>
    
    <td>
      Tools for testing the code that reads your configs
    </td>
    
    <td>
      21
    </td>
    
    <td>
      8
    </td>
  </tr>
</tbody>
</table>

The Compose artifact depends only on the Compose runtime, so it does not pull `compose-ui` or Material into an application that does not already have them.

Config evaluation is synchronous and reads config state the client already holds in memory, which is what makes it safe to call from a composable or from a view binding. Telemetry about those evaluations is aggregated and reported on its own coroutine, so evaluating a config never waits on the network.

## Installation

The SDK is published to the [ConfigDirector Maven repository](https://docs.configdirector.com/sdks/maven-repository). Add the repository to `settings.gradle.kts` or `settings.gradle`, next to `google()` and `mavenCentral()`:

<code-group>

```kotlin [settings.gradle.kts]
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        exclusiveContent {
            forRepository {
                maven {
                    name = "ConfigDirector"
                    url = uri("https://maven.configdirector.com")
                }
            }
            filter {
                includeGroup("com.configdirector")
            }
        }
    }
}
```

```groovy [settings.gradle]
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        exclusiveContent {
            forRepository {
                maven {
                    name = 'ConfigDirector'
                    url = 'https://maven.configdirector.com'
                }
            }
            filter {
                includeGroup 'com.configdirector'
            }
        }
    }
}
```

</code-group>

Then add the dependencies to your app module:

<code-group>

```kotlin [build.gradle.kts]
dependencies {
    implementation("com.configdirector:android-sdk:1.10.0")

    // Optional, for Jetpack Compose applications
    implementation("com.configdirector:android-sdk-compose:1.10.0")
}
```

```groovy [build.gradle]
dependencies {
    implementation 'com.configdirector:android-sdk:1.10.0'

    // Optional, for Jetpack Compose applications
    implementation 'com.configdirector:android-sdk-compose:1.10.0'
}
```

```toml [libs.versions.toml]
[versions]
configdirector = "1.10.0"

[libraries]
configdirector-android-sdk = { module = "com.configdirector:android-sdk", version.ref = "configdirector" }
# Optional, for Jetpack Compose applications
configdirector-android-sdk-compose = { module = "com.configdirector:android-sdk-compose", version.ref = "configdirector" }
```

</code-group>

The SDK declares the `INTERNET` permission, which is merged into your application's manifest, so there is nothing to add there.

## Configure and initialize the client

1. Create an instance of the client providing an Android context and your client SDK key. You can retrieve a client SDK key for each environment under `SDK keys` in the dashboard's navigation panel.
2. Initialize the client to initiate its connection lifecycle.

<code-group>

```kotlin [ConfigDirectorSetup.kt]
import com.configdirector.ConfigDirectorClient

// Creating the client makes no network calls. It throws only when the SDK key is
// blank or an option holds an unusable value.
val client = ConfigDirectorClient(applicationContext, "YOUR-CLIENT-SDK-KEY")

// Connects and waits until config values are received, or until it times out.
// After a timeout the client keeps trying to connect in the background.
client.initialize()
```

```java [ConfigDirectorSetup.java]
import com.configdirector.ConfigDirectorClient;

// Creating the client makes no network calls. It throws only when the SDK key is
// blank or an option holds an unusable value.
ConfigDirectorClient client = new ConfigDirectorClient(getApplicationContext(), "YOUR-CLIENT-SDK-KEY");

// Connects, and calls back on the main thread once config values are received or
// the attempt times out. After a timeout the client keeps trying in the background.
client.initialize(null, () -> Log.i("MyApp", "ConfigDirector ready: " + client.isReady()));
```

</code-group>

The client is thread safe. Create one and share it for the lifetime of the app.

`initialize` is a `suspend` function in Kotlin, so it is called from a coroutine. The overload taking a `CompletionCallback` is the one to use from Java, and from anywhere in Kotlin that has no coroutine to run in.

<note>

Before the client is initialized, config values will evaluate to the default value provided in code.

</note>

The constructor throws a `ConfigDirectorValidationException` in only two cases, both of which are programming errors rather than runtime conditions: a blank client SDK key outside [offline mode](#run-without-a-connection), and an option that cannot be used, such as a negative timeout or a base URL that is not absolute. Connection failures are not thrown — `initialize` returns normally whether or not config state arrived, and `isReady` tells you which happened.

Most applications create a single client instance and initialize it during startup. That usually means owning it in the `Application`, so every screen shares one client:

<code-group>

```kotlin [MyApplication.kt]
import android.app.Application
import com.configdirector.ConfigDirectorClient
import com.configdirector.ConfigDirectorContext
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class MyApplication : Application() {

    lateinit var client: ConfigDirectorClient
        private set

    override fun onCreate() {
        super.onCreate()

        client = ConfigDirectorClient(this, "YOUR-CLIENT-SDK-KEY")

        MainScope().launch {
            client.initialize(ConfigDirectorContext.build { id("user-123") })
        }
    }
}
```

```java [MyApplication.java]
import android.app.Application;
import com.configdirector.ConfigDirectorClient;
import com.configdirector.ConfigDirectorContext;

public class MyApplication extends Application {

  private ConfigDirectorClient client;

  @Override
  public void onCreate() {
    super.onCreate();

    client = new ConfigDirectorClient(this, "YOUR-CLIENT-SDK-KEY");

    client.initialize(
        ConfigDirectorContext.builder().id("user-123").build(),
        () -> Log.i("MyApp", "ConfigDirector ready: " + client.isReady()));
  }

  public ConfigDirectorClient getClient() {
    return client;
  }
}
```

</code-group>

<note>

The client watches the application behind the context it was given so it can release its network connection while the app is backgrounded. Pass it any context — the application behind it is what matters. If the context does not belong to an `Application`, the SDK logs a warning and leaves the connection running for you to manage with [`pauseNetwork()` and `resumeNetwork()`](#pausenetwork-and-resumenetwork).

</note>

Nothing needs to close the client: it lives as long as the process, and Android reclaims everything when the process ends. Call [`close()`](#close) when an application wants the client gone before that, on sign-out for instance.

### Additional configuration options

These options can be passed in to `ClientOptions`, which is built with `ClientOptions.build { }` from Kotlin and `ClientOptions.builder()` from Java. They are read once when the client is created; changing them afterwards has no effect.

#### `metadata`

The `metadata` option allows you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

Whichever of the two you leave unset is read from the application when the client is created — the name from the application label and the version from `versionName` — so most applications do not need to set either one. When one cannot be read, the client says so at the `INFO` log level.

<code-group>

```kotlin [ConfigDirectorSetup.kt]
val client = ConfigDirectorClient(
    applicationContext,
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.build {
        metadata("YOUR-APP-NAME", "1.0.2")
    },
)
```

```java [ConfigDirectorSetup.java]
ConfigDirectorClient client = new ConfigDirectorClient(
    getApplicationContext(),
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.builder()
        .metadata(new Metadata("YOUR-APP-NAME", "1.0.2"))
        .build());
```

</code-group>

#### `logger`

By default, the SDK logs to logcat under the `ConfigDirector` tag, and it is set to log warnings and errors only. You can configure a `logger` by either creating an `AndroidLogger` with a different log level, or by implementing the `ConfigDirectorLogger` interface to provide your own logger. The interface can be used to create an adapter to another logging library.

Configure the default logger to a different level:

<code-group>

```kotlin [ConfigDirectorSetup.kt]
val client = ConfigDirectorClient(
    applicationContext,
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.build { logger(AndroidLogger(LogLevel.DEBUG)) },
)
```

```java [ConfigDirectorSetup.java]
ConfigDirectorClient client = new ConfigDirectorClient(
    getApplicationContext(),
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.builder().logger(new AndroidLogger(LogLevel.DEBUG)).build());
```

</code-group>

The available levels are `OFF`, `ERROR`, `WARN` (the default), `INFO` and `DEBUG`.

Implement your own logger adapter:

<code-group>

```kotlin [MyLogger.kt]
import com.configdirector.ConfigDirectorLogger
import com.configdirector.LogLevel

class MyLogger : ConfigDirectorLogger {
    // Messages more verbose than this level are never passed to `log`.
    override val level: LogLevel = LogLevel.INFO

    override fun log(level: LogLevel, message: String, error: Throwable?) {
        // your specific logging library implementation here
    }
}

val client = ConfigDirectorClient(
    applicationContext,
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.build { logger(MyLogger()) },
)
```

```java [MyLogger.java]
import com.configdirector.ConfigDirectorLogger;
import com.configdirector.LogLevel;

public final class MyLogger implements ConfigDirectorLogger {

  // Messages more verbose than this level are never passed to `log`.
  @Override
  public LogLevel getLevel() {
    return LogLevel.INFO;
  }

  @Override
  public void log(LogLevel level, String message, Throwable error) {
    // your specific logging library implementation here
  }
}
```

</code-group>

#### `connection`

`ConnectionOptions` accepts six optional values:

- `mode`
  - The connection mode, which can be `ConnectionMode.STREAMING`, `ConnectionMode.POLLING` or `ConnectionMode.OFFLINE`. It is recommended to use the default of `STREAMING` unless you have a specific need to use `POLLING` instead. In `OFFLINE` mode the client never connects to ConfigDirector and serves the values you give it; see [Run without a connection](#run-without-a-connection).
  - `STREAMING` holds a connection open and receives changes as they happen, reconnecting on its own with a backoff. The server sends a keepalive at least every 15 seconds, so a connection that stays silent for 45 seconds is dropped and reopened the same way.
  - Defaults to `ConnectionMode.STREAMING`
- `values`
  - The values to serve in `OFFLINE` mode, as a `Map` keyed by config key. They can be given only in `OFFLINE` mode. See [Run without a connection](#run-without-a-connection).
- `pollingIntervalMillis`
  - How often to re-fetch config state, in milliseconds, when `mode` is `ConnectionMode.POLLING`. It has no effect in any other mode. A value below the minimum of `30_000` (30 seconds) is raised to `30_000` and a warning is logged. See [Polling intervals](https://docs.configdirector.com/getting-started/architecture#polling-intervals).
  - Defaults to `60_000` (60 seconds)
- `timeoutMillis`
  - The timeout to be used in initialization and when updating the context. This is how long `initialize` will wait for data from ConfigDirector services before returning. If the timeout is reached, `initialize` will return but the client will still be in an unready status and returning default values. The client will continue to attempt to connect and retrieve config values in the background.
  - If your application is used in environments where the users frequently have poor or no connection, you may want to use a lower timeout, or simply don't await the `initialize` call.
  - It has no effect in `OFFLINE` mode.
  - Defaults to `3_000` (3 seconds)
- `pausesWhileBackgrounded`
  - Whether to pause the connection while the app is in the background and resume it when the app returns to the foreground. Android stops background connections on its own, so this is enabled by default. Set it to `false` to manage the connection yourself with `pauseNetwork()` and `resumeNetwork()`. It has no effect in `OFFLINE` mode.
  - Defaults to `true`
- `baseUrl`
  - The base URL used to connect to ConfigDirector services.
  - This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services. It has no effect in `OFFLINE` mode.

<code-group>

```kotlin [ConfigDirectorSetup.kt]
val client = ConfigDirectorClient(
    applicationContext,
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.build {
        connection {
            mode(ConnectionMode.POLLING)
            pollingIntervalMillis(600_000L)
            timeoutMillis(2_000L)
        }
    },
)
```

```java [ConfigDirectorSetup.java]
ConfigDirectorClient client = new ConfigDirectorClient(
    getApplicationContext(),
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.builder()
        .connection(
            ConnectionOptions.builder()
                .mode(ConnectionMode.POLLING)
                .pollingIntervalMillis(600_000L)
                .timeoutMillis(2_000L)
                .build())
        .build());
```

</code-group>

Settings are checked as they are built, so an unusable one throws a `ConfigDirectorValidationException` where it was written rather than becoming a client that quietly never updates. In `OFFLINE` mode the timeout and the base URL are not used, so they are not checked.

#### `caching`

`CachingOptions` decides whether the client keeps the last values it received on the device and serves them on the next launch until live values arrive, and where. It is on by default; see [Values kept on the device](#values-kept-on-the-device) for its two fields.

### Events

Events notify you of some key actions from the client. `addEventListener` registers a listener for the client's lifecycle changes, and `addEvaluationListener` registers one for every individual config evaluation. Both are called on the main thread, and both return a `Subscription` you close to stop listening. Kotlin callers have the same two as flows, `client.events` and `client.evaluations`; each collection is independent, so several parts of your app can observe them at once, and every flow completes when the client is closed.

<code-group>

```kotlin [ConfigDirectorSetup.kt]
import com.configdirector.ClientEvent
import com.configdirector.events

lifecycleScope.launch {
    client.events.collect { event ->
        when (event) {
            is ClientEvent.Ready -> Log.i("MyApp", "Client is ready after ${event.reason}")
            is ClientEvent.ConfigsUpdated -> Log.i("MyApp", "Configs updated: ${event.keys}")
            is ClientEvent.ContextUpdated -> Log.i("MyApp", "Context updated: ${event.context?.id}")
            is ClientEvent.CachedValuesLoaded -> Log.i("MyApp", "Serving the values kept on the device until live values arrive")
        }
    }
}
```

```java [ConfigDirectorSetup.java]
import com.configdirector.ClientEvent;
import com.configdirector.Subscription;

Subscription subscription = client.addEventListener(event -> {
  if (event instanceof ClientEvent.Ready) {
    Log.i("MyApp", "Client is ready after " + ((ClientEvent.Ready) event).getReason());
  } else if (event instanceof ClientEvent.ConfigsUpdated) {
    Log.i("MyApp", "Configs updated: " + ((ClientEvent.ConfigsUpdated) event).getKeys());
  }
});

// Close the subscription to stop listening
subscription.close();
```

</code-group>

The following events are published to an event listener:

- `ClientEvent.Ready`
  - Emitted when the client is initialized, or after reconnection due to a context update or a resumed network connection. When this event is emitted it means the client has received a payload from the ConfigDirector servers and is ready to evaluate configs.
  - `reason` - A `ConnectReason`, the action that triggered the client to connect/reconnect, which can be `ConnectReason.INITIALIZATION`, `ConnectReason.CONTEXT_UPDATE`, or `ConnectReason.NETWORK_RESUME`.
- `ClientEvent.ConfigsUpdated`
  - Emitted when a payload is received from the ConfigDirector servers with config data. It is emitted during initialization or context update when an entire config payload is received. After initialization or context update, it is emitted when updates are pushed from the server (or discovered via polling if that connection mode is used).
  - `keys` - A `List<String>` listing the config keys that were included in the payload from the server. On a delta update, these are only the configs that changed.
  - `removedKeys` - A `List<String>` listing the keys of configs the payload removed. A config is removed when a full payload no longer includes it. Empty when nothing was removed, and always empty on a delta update.
- `ClientEvent.ContextUpdated`
  - Emitted whenever the context takes effect, including during initialization. It can come before or after `ClientEvent.Ready`, so it should not be relied upon as a lifecycle event but rather as an informational event to track updates to the context.
  - `context` - The `ConfigDirectorContext` the client is now evaluating against. It can be `null`.
- `ClientEvent.CachedValuesLoaded`
  - Emitted when the values kept on the device from the last payload are loaded and served, before live values arrive. It is followed by `ClientEvent.ConfigsUpdated` listing their keys. See [Values kept on the device](#values-kept-on-the-device). The event carries nothing.

An evaluation listener is handed a `ConfigEvaluation` every time a config is evaluated, which can be useful for debugging what a screen actually read, and for capturing additional context for analytics events. This includes every read through a getter and every re-evaluation a watch makes. A `ConfigEvaluation` carries:

- `key: String` - The config key that was evaluated.
- `value: Any` - The value the config evaluated to. It can be the default value provided by the caller, for example if the config was evaluated before the client was initialized. It is a `Boolean`, `String`, `Integer` or `Double`, matching the accessor the config was read with.
- `valueId: String?` - The value ID, a stable hash of the value that you can send to a third party rather than the `value`. This can be useful for large values, like a JSON config, or to avoid disclosing the values themselves. It is `null` if the evaluation had to fall back to the in-code default value. To report an experiment to an analytics tool, send the variation instead: the pages for [Amplitude](https://docs.configdirector.com/integrations/analytics/amplitude), [Mixpanel](https://docs.configdirector.com/integrations/analytics/mixpanel), [Google Analytics 4](https://docs.configdirector.com/integrations/analytics/ga4), [Segment](https://docs.configdirector.com/integrations/analytics/segment) and [PostHog](https://docs.configdirector.com/integrations/analytics/posthog) name the event each one reads.
- `variation: Variation?` - The variation that was served, with its `id` and `name`. The `id` stays the same when the variation is renamed, and `name` is `null` for a variation without one. It is `null` when the config has no variations or the in-code default value is returned. A value served from the values kept on the device carries it too, unless an earlier version of the SDK kept that value. Versions of the SDK before 1.10.0 do not report it.
- `isDefaultValue: Boolean` - Whether or not the evaluation fell back to the default value provided in code.
- `context: ConfigDirectorContext?` - The context the config was evaluated against, if one was set.
- `reason: EvaluationReason` - The reason for the evaluation resolution. In the case the config successfully evaluated based on server-provided targeting rules, it will be `FOUND_MATCH`. A value served from the values kept on the device, before live values arrive, reports `CACHED`; see [Values kept on the device](#values-kept-on-the-device). If the evaluation had to fall back to the default value, the `reason` will encode why the fallback was required:
  - `CLIENT_NOT_READY` - The evaluation happened before the client finished initialization.
  - `CONFIG_STATE_MISSING` - The requested config key was not present in the payload received from the server. This could be due to an incorrect config key, or a config that was not enabled to be available to client SDKs.
  - `VALUE_MISSING` - The config had no value for the current context.
  - `INVALID_NUMBER` - The config was requested as a number but the value received from the server could not be converted to a number.
  - `INVALID_BOOLEAN` - The config was requested as a boolean but the value received from the server could not be converted to a boolean.
  - `INVALID_JSON` - The config was requested as JSON but the value received from the server could not be read as a JSON document.
  - `TYPE_MISMATCH` - The config was requested with a data type that did not match the type of the config and no reasonable type conversion was possible.<br />

`EvaluationReason` also lists `ROLLOUT_SKIPPED_NO_IDENTIFIER`. It comes from server SDKs and this SDK never returns it, so a `when` that lists every reason needs a branch for it and nothing more.

```kotlin [ConfigDirectorSetup.kt]
import com.configdirector.evaluations

lifecycleScope.launch {
    client.evaluations
        .filter { it.isDefaultValue }
        .collect { Log.w("MyApp", "'${it.key}' fell back to its default: ${it.reason.wireName}") }
}
```

<warning>

Do not read a config from an evaluation listener, and do not drive state from `evaluations` that a composable reads a config from. The read publishes another evaluation, which recomposes, which reads the config again.

</warning>

### Run without a connection

Set the connection `mode` to `ConnectionMode.OFFLINE` to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline client opens no connection and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no config's lifecycle state changes. Every context receives the same value and targeting rules are not applied. An offline client also leaves the device alone: it reads nothing about your app and stores nothing in `SharedPreferences`. To test the code that reads your configs rather than run the whole application, use a test client instead; see [Test your code](#test-your-code).

An offline client needs no client SDK key. Create it with the constructor that takes only a context and the options, as below, or pass a blank key, such as a `BuildConfig` field left empty in a test build.

Give the values inline, with one value per config key. Your application decides where they come from, for example a map in a test build or a JSON asset it bundles:

<code-group>

```kotlin [ConfigDirectorSetup.kt]
import com.configdirector.ClientOptions
import com.configdirector.ConfigDirectorClient
import com.configdirector.ConnectionMode
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

val client = ConfigDirectorClient(
    applicationContext,
    ClientOptions.build {
        connection {
            mode(ConnectionMode.OFFLINE)
            values(mapOf("new-checkout" to true, "max-items" to 20))
        }
    },
)

MainScope().launch { client.initialize() }
```

```java [ConfigDirectorSetup.java]
import com.configdirector.ClientOptions;
import com.configdirector.ConfigDirectorClient;
import com.configdirector.ConnectionMode;
import com.configdirector.ConnectionOptions;
import java.util.HashMap;
import java.util.Map;

Map<String, Object> values = new HashMap<>();
values.put("new-checkout", true);
values.put("max-items", 20);

ConfigDirectorClient client = new ConfigDirectorClient(
    getApplicationContext(),
    ClientOptions.builder()
        .connection(
            ConnectionOptions.builder()
                .mode(ConnectionMode.OFFLINE)
                .values(values)
                .build())
        .build());

client.initialize(null, () -> Log.i("MyApp", "ConfigDirector ready: " + client.isReady()));
```

</code-group>

Each value's type decides its config's type: a `Boolean` is a `boolean` config, an `Int` or a `Long` an `integer` config, a `Float` or a `Double` a `float` config, a `String` a `string` config, and a `Map` with `String` keys or a `List` a `json` config. A JSON library that reads an object into a `Map`, such as Gson, Moshi or Jackson, gives values of these types; Gson and Moshi read every number as a `Double`, so `20` in a JSON asset is a float config, which `getInt` still reads as `20`. A value is read by the same rules as a value served by ConfigDirector, so a boolean read with `getString`, for instance, returns the in-code default value with the `TYPE_MISMATCH` reason.

`initialize` returns once the values are loaded, with the client ready and `ClientEvent.Ready` delivered once. A watch registered before `initialize` is handed the in-code default value and then the offline value once `initialize` loads it; one registered after is handed the offline value. Neither is called again, since offline values do not change. Calling `initialize` a second time hands the same values over again and delivers `Ready` again. `updateContext` takes the new context at once and changes no value, and `pauseNetwork` and `resumeNetwork` do nothing. `pollingIntervalMillis`, `timeoutMillis`, `baseUrl` and `pausesWhileBackgrounded` have no effect.

With `ConnectionMode.OFFLINE` and no `values`, the client is ready at once and every config returns its in-code default value with the `CONFIG_STATE_MISSING` reason.

Building the connection options throws a `ConfigDirectorValidationException` when the values cannot be used: a value that is `null`, which a Java map can hold, a number that is not finite, a value of a type not listed above, a blank key, or `values` given in `STREAMING` or `POLLING` mode. A test run with a wrong value fails where the options are built instead of passing on in-code default values.

If you come from LaunchDarkly, a map of values is what LaunchDarkly calls "flags from files", and `OFFLINE` with no values is its "offline mode".

### Values kept on the device

By default, the client keeps the last values it received from ConfigDirector on the device, in the app's `SharedPreferences`, and serves them on the next launch of the same context until live values arrive. An app opened without a network, after at least one successful connection, shows the values ConfigDirector last sent instead of the in-code default values. Every evaluation served this way reports the reason `CACHED`, with `isDefaultValue` set to `false`; a key the kept values do not carry reports `CLIENT_NOT_READY`, as before any values arrive.

The client is not ready while it serves values kept on the device: `isReady` stays `false`, `isInitializing` stays `true`, `initialize` still waits for live values or its `timeoutMillis`, and `ClientEvent.Ready` is delivered once live values arrive and replace them. `ClientEvent.CachedValuesLoaded` is delivered when the kept values are loaded, followed by `ClientEvent.ConfigsUpdated` listing their keys, and watches are handed the kept values. When the first live payload replaces them, its `ConfigsUpdated` lists the kept keys it no longer carries in `removedKeys`.

The values are kept for the context they were evaluated for, and served on the next launch only when the launch context has the same `kind` and `id`. A launch with another context serves the in-code default values until live values arrive, which then replace the kept values. A context without an `id` matches on the same install, as long as the app has not been uninstalled, because ConfigDirector derives its identifier from the instance ID the SDK stores; a context without an `id` keeps its percentage rollout bucket for as long as that instance ID lasts. Name, traits, app name and app version take no part in the match: live values correct them within a second when there is a network. Once the client is running, updating the context keeps serving the current values until the new context's values arrive, as it does with live values.

Turn it off, or supply your own store, with the `caching` option:

- `enabled`
  - Whether to keep the last values received. With `false`, nothing is read or written, even when a `provider` is given.
  - Defaults to `true`
- `provider`
  - A store of your own, for example an encrypted one, implementing `CachingProvider`: `read()` returns the stored entry or `null`, `write(value)` replaces it, `remove()` deletes it, and `sizeLimit()` returns the largest entry, in bytes, the store accepts. `read`, `write` and `remove` are `suspend` functions, so a provider is written in Kotlin; a Java app keeps the default store or turns caching off. One provider instance serves one client.
  - Defaults to the app's `SharedPreferences`, under a key derived from the client SDK key, with a size limit of 256 KB

<code-group>

```kotlin [ConfigDirectorSetup.kt]
val client = ConfigDirectorClient(
    applicationContext,
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.build {
        caching {
            enabled(true)
            provider(MyEncryptedStore())
        }
    },
)
```

```java [ConfigDirectorSetup.java]
ConfigDirectorClient client = new ConfigDirectorClient(
    getApplicationContext(),
    "YOUR-CLIENT-SDK-KEY",
    ClientOptions.builder()
        .caching(CachingOptions.builder().enabled(false).build())
        .build());
```

</code-group>

The entry is one string whose format belongs to the SDK and may change between SDK versions; an entry a newer SDK cannot read is removed. Before every write the SDK measures the entry against `sizeLimit()`; above it, the entry is removed and a warning is logged once, so the device never serves values that no longer reflect the set. A provider that fails to read, write or remove is logged once and never stops the client: the worst outcome is the in-code default values. Keeping values on the device is ignored in `OFFLINE` mode, and a test client from `android-sdk-testing` keeps nothing.

If you come from Firebase Remote Config, this is what activated values persisting across restarts gives you; if you come from LaunchDarkly, it is what its mobile SDKs do with the flags they cache on the device.

## Retrieve config values

To synchronously retrieve config values, use the client's typed getters: `getBoolean`, `getString`, `getInt`, `getDouble`, `getJsonObject` and `getJsonArray`. Each requires two arguments. The first argument is the config key, and the second is the default value to be returned if the client has not yet received config values from ConfigDirector services. Kotlin callers also have `client.value(key, default)`, which takes the type from the default value.

You can also subscribe to config value changes via the matching watches: `watchBoolean`, `watchString`, `watchInt`, `watchDouble`, `watchJsonObject` and `watchJsonArray`. Each takes the config key, the default value, and a listener that is handed the config's current value straight away and then every time the evaluated value changes, whether because it was edited in the ConfigDirector dashboard or because the context was updated. Consecutive identical values are not delivered again. When a full payload no longer includes the watched config, the listener is handed the default value, as a getter would now return it. Close the returned `Subscription` to stop watching. In Kotlin, `client.values(key, default)` is the same thing as a `Flow`, and canceling the collector stops watching.

<code-group>

```kotlin [MainActivity.kt]
import com.configdirector.value
import com.configdirector.values

// Retrieve the current value. The default value decides the type the config
// is read as, and is returned until the client is ready.
val darkMode = client.value("my-config-key", false)

// Subscribe to value updates. The flow emits the current value right away
// and then every time the evaluated value changes.
lifecycleScope.launch {
    client.values("my-config-key", false).collect { darkMode ->
        Log.i("MyApp", "Value updated: $darkMode")
    }
}
```

```java [MainActivity.java]
import com.configdirector.Subscription;

// Retrieve the current value. There is a getter per type a config can be read
// as, and each returns the default value until the client is ready.
boolean darkMode = client.getBoolean("my-config-key", false);

// Subscribe to value updates. The listener is called on the main thread with the
// current value, and then every time the evaluated value changes.
Subscription subscription = client.watchBoolean(
    "my-config-key",
    false,
    value -> Log.i("MyApp", "Value updated: " + value));

// Close the subscription to stop watching
subscription.close();
```

```kotlin [SampleScreen.kt (Compose)]
import com.configdirector.compose.configValue

@Composable
fun SampleScreen() {
    // Recomposes whenever the evaluated value changes.
    val darkMode = configValue("my-config-key", false)

    Text("my-config-key: $darkMode")
}
```

</code-group>

There is one getter and one watch per type a config can be read as, so a default value of any other type is a compile error rather than a failure at runtime. If the served value does not match the type it is read as, the SDK will attempt to convert it. If the conversion fails, it will return the default value. Mismatched types at runtime are captured by the telemetry collector and will surface as warnings in the ConfigDirector dashboard.

```kotlin [MainActivity.kt]
client.getString("my-string-config-key", "Default")

client.getInt("my-integer-config-key", 100)

client.getDouble("my-decimal-config-key", 1.5)

client.getBoolean("my-boolean-config-key", false)
```

A string, enum, URL, or custom config can be read as a string, and so can a JSON config, as its raw document. A boolean, integer, or float config read as a string evaluates to the default value with the `TYPE_MISMATCH` reason. A value written as a decimal and read with `getInt` is truncated.

### JSON configs

A config declared as JSON in the ConfigDirector dashboard is read with `getJsonObject` or `getJsonArray`, depending on the shape of its document. The values inside are `String`, `Number`, `Boolean`, `List`, `Map`, or null, and the document cannot be modified. Only a JSON config reads as one; read it as a string to get its raw document.

<code-group>

```kotlin [MainActivity.kt]
val theme = client.getJsonObject("theme", mapOf("primary" to "#101010"))
val primary = theme["primary"] as? String

val regions = client.getJsonArray("regions", listOf("us-east"))
```

```java [MainActivity.java]
Map<String, Object> theme = client.getJsonObject("theme", Collections.singletonMap("primary", "#101010"));
String primary = (String) theme.get("primary");

List<Object> regions = client.getJsonArray("regions", Collections.singletonList("us-east"));
```

</code-group>

### Reading configs in Jetpack Compose

The `android-sdk-compose` artifact reads configs as Compose state, so a composable recomposes on its own whenever an evaluated value changes.

Wrap your content in a `ConfigDirectorProvider` and every binding below it reads from that client:

```kotlin [MainActivity.kt]
import com.configdirector.compose.ConfigDirectorProvider

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val client = (application as MyApplication).client
        setContent {
            ConfigDirectorProvider(client) {
                MaterialTheme { HomeScreen() }
            }
        }
    }
}
```

`configValue` then reads a config anywhere inside it, with one overload per type a config can be read as. Until the client is ready, and for a value that cannot be read as the requested type, it is the default value:

```kotlin [HomeScreen.kt]
import com.configdirector.compose.configContext
import com.configdirector.compose.configValue
import com.configdirector.compose.isClientReady

@Composable
fun HomeScreen() {
    val darkMode = configValue("dark-mode", false)
    val greeting = configValue("greeting", "Hello")

    // Recomposes when config state arrives, which is useful to show a loading
    // state rather than flashing the in-code default value on a slow connection.
    if (!isClientReady()) {
        LoadingScreen()
        return
    }

    Text(text = greeting, color = if (darkMode) Color.White else Color.Black)
}
```

`isClientReady()` and `configContext()` expose the client's readiness and its current context as state, recomposing when either changes.

<note>

Each binding takes the client from `LocalConfigDirectorClient` unless one is passed to it explicitly. Reading a binding with no provider above it in the tree fails rather than serving default values that look like real ones.

</note>

### Reading configs with framework views

With framework views, register a watch when the view is created and close its subscription when the view goes away:

```kotlin [MainActivity.kt]
class MainActivity : AppCompatActivity() {

    private var subscription: Subscription? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val client = (application as MyApplication).client
        subscription = client.watchBoolean("dark-mode", false) { darkMode ->
            // Called on the main thread with the current value, and on every change.
            findViewById<Switch>(R.id.dark_mode).isChecked = darkMode
        }
    }

    override fun onDestroy() {
        subscription?.close()
        super.onDestroy()
    }
}
```

## Update the context

A context can be provided when initializing the client:

<code-group>

```kotlin [ConfigDirectorSetup.kt]
import com.configdirector.ConfigDirectorClient
import com.configdirector.ConfigDirectorContext

val client = ConfigDirectorClient(applicationContext, "YOUR-CLIENT-SDK-KEY")

client.initialize(
    ConfigDirectorContext.build {
        id("12345")
        name("Example User")
        // Any arbitrary traits which can be referenced in targeting rules
        trait("region", "North America")
    },
)
```

```java [ConfigDirectorSetup.java]
import com.configdirector.ConfigDirectorClient;
import com.configdirector.ConfigDirectorContext;

ConfigDirectorClient client = new ConfigDirectorClient(getApplicationContext(), "YOUR-CLIENT-SDK-KEY");

ConfigDirectorContext context = ConfigDirectorContext.builder()
    .id("12345")
    .name("Example User")
    // Any arbitrary traits which can be referenced in targeting rules
    .trait("region", "North America")
    .build();

client.initialize(context, () -> Log.i("MyApp", "ConfigDirector ready: " + client.isReady()));
```

</code-group>

The context can also be updated via `updateContext`:

<code-group>

```kotlin [MainActivity.kt]
import com.configdirector.ConfigDirectorContext

client.updateContext(
    ConfigDirectorContext.build {
        id("654321")
        name("Another User")
        trait("region", "Australia")
    },
)

// Update it to an anonymous context when a user signs out. Leaving `id` unset
// makes ConfigDirector derive an identifier that lasts until the app is uninstalled.
client.updateContext(ConfigDirectorContext.build { anonymous(true) })
```

```java [MainActivity.java]
import com.configdirector.ConfigDirectorContext;

client.updateContext(
    ConfigDirectorContext.builder()
        .id("654321")
        .name("Another User")
        .trait("region", "Australia")
        .build(),
    () -> Log.i("MyApp", "Context updated"));

// Update it to an anonymous context when a user signs out. Leaving `id` unset
// makes ConfigDirector derive an identifier that lasts until the app is uninstalled.
client.updateContext(
    ConfigDirectorContext.builder().anonymous(true).build(),
    () -> Log.i("MyApp", "Signed out"));
```

</code-group>

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with `kind`:

<code-group>

```kotlin [MainActivity.kt]
client.updateContext(
    ConfigDirectorContext.build {
        id("acme")
        kind("tenant")
        name("Acme Inc.")
        trait("plan", "enterprise")
    },
)
```

```java [MainActivity.java]
client.updateContext(
    ConfigDirectorContext.builder()
        .id("acme")
        .kind("tenant")
        .name("Acme Inc.")
        .trait("plan", "enterprise")
        .build(),
    () -> Log.i("MyApp", "Context updated"));
```

</code-group>

Leaving `kind` out means `user`. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and configs are evaluated as if no context had been given. Context kinds are available from version 1.8.0 of the SDK.

<note>

In client SDKs (browser and mobile), updating the context re-establishes a new connection to ConfigDirector servers with the new context. While the new connection is in flight, config values will continue to evaluate to the currently cached values from the prior context.<br />


Awaiting `updateContext` will wait until the new config values are downloaded or the connection times out. In the case of a timeout, the client will continue to attempt to connect with the new context in the background.

</note>

Traits are JSON-shaped values: `String`, `Number`, `Boolean`, `List`, `Map`, or null. A trait of any other type could never match a targeting rule, so building the context throws a `ConfigDirectorValidationException` rather than sending something the server cannot evaluate.

```kotlin [MainActivity.kt]
client.updateContext(
    ConfigDirectorContext.build {
        id("user-123")
        name("Ada Lovelace")
        traits(
            mapOf(
                "plan" to "pro",
                "seats" to 12,
                "beta" to true,
                "regions" to listOf("us-east", "eu-west"),
            ),
        )
    },
)
```

For a signed-out user, set `anonymous` to `true`. The values are still used to evaluate targeting rules, but the context is not persisted and does not appear in the dashboard.

The SDK keeps an instance ID in the app's `SharedPreferences` until the app is uninstalled, and ConfigDirector derives the identifier of a context without an `id` from it. A person who uses the app without signing in keeps that identifier, and their percentage rollout bucket, from one app start to the next, and counts as one [monthly active user](https://docs.configdirector.com/getting-started/pricing-and-billing#billing-metrics) however often they open the app.

## Track events

`track` reports to ConfigDirector that something happened in your application, such as a completed checkout. ConfigDirector shows tracked events on the Live feed and counts them for each variation of a running experiment; see [Tracked events](https://docs.configdirector.com/monitoring/activity#tracked-events).

`track` accepts the name of the event and optional `TrackOptions` with a `value` and `details`, and reports the event for the client's current context:

<code-group>

```kotlin [MainActivity.kt]
import com.configdirector.TrackOptions

client.track(
    "checkout-completed",
    TrackOptions(value = 49.9, details = mapOf("plan" to "pro", "seats" to 3)),
)

client.track("tutorial-skipped")
```

```java [MainActivity.java]
import com.configdirector.TrackOptions;
import java.util.HashMap;
import java.util.Map;

Map<String, Object> details = new HashMap<>();
details.put("plan", "pro");
details.put("seats", 3);

client.track("checkout-completed", new TrackOptions(49.9, details));

client.track("tutorial-skipped");
```

</code-group>

- `value` is a number the event measures, such as an amount of money, a count or a duration. It can be any `Number`, and an `Int`, a `Long`, a `BigInteger` or a `BigDecimal` is sent with every digit, so `BigDecimal("49.90")` arrives as `49.90`.
- `details` is a `Map` with `String` keys describing the event. Its values are `String`, `Number`, `Boolean`, a `Map` with `String` keys, a `Collection`, or null. A `java.util.Date`, `Instant`, `OffsetDateTime` or `ZonedDateTime` is sent as ISO 8601 text in UTC, such as `2026-12-01T00:00:00.000Z`, and a number that is not finite as null.

An event counts for an experiment only when the current context has an `id`, the same one the experiment's config was evaluated for. Before the client has a context, or for a context without an `id`, the event is still reported and counts for no experiment. For a context marked `anonymous`, the event is reported without the `id`, so it counts for no experiment either. The current context is what [`context`](#context) returns, so while a context update is in flight the event goes with the previous context.

`track` returns nothing and never throws, as long as a Java caller does not pass a null name, which is a `NullPointerException`. The event is sent with the SDK's next telemetry report, every 30 seconds and when the app goes to the background. In [`OFFLINE` mode](#run-without-a-connection) and after `close`, `track` does nothing. The SDK applies these limits, and logs one warning for each of them per telemetry report:

<table>
<thead>
  <tr>
    <th>
      Limit
    </th>
    
    <th>
      Beyond it
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      An event name of 1 to 150 characters
    </td>
    
    <td>
      The event is not reported.
    </td>
  </tr>
  
  <tr>
    <td>
      1,000 tracked events in one telemetry report
    </td>
    
    <td>
      Further events are not reported until that report is sent.
    </td>
  </tr>
  
  <tr>
    <td>
      Details of up to 20 top-level keys and 1 KB as JSON, holding only the types of value above
    </td>
    
    <td>
      The details are left out and the event is still reported.
    </td>
  </tr>
  
  <tr>
    <td>
      A <code>
        value
      </code>
      
       that is a finite number
    </td>
    
    <td>
      The value is left out and the event is still reported.
    </td>
  </tr>
</tbody>
</table>

ConfigDirector applies limits of its own to the events it stores; see [Limits](https://docs.configdirector.com/monitoring/activity#limits).

From version 1.10.0 of the SDK, each evaluation it reports also says which variation was served and which percentage rollout and share served it. That is how ConfigDirector counts the contexts each variation of an experiment reached.

`track` is available from version 1.10.0 of the SDK, which adds the `TrackOptions` class.

## Other useful client features

The client provides additional properties and methods.

### `evaluate`

Evaluates a config the way the getters do and returns the `ConfigEvaluation` behind it — the value, whether it is the in-code default value, the `reason`, the `valueId`, the `variation` and the `context` — instead of the value alone. There is one method per type a config can be read as: `evaluateBoolean`, `evaluateString`, `evaluateInt`, `evaluateDouble`, `evaluateJsonObject` and `evaluateJsonArray`. Kotlin callers also have `client.evaluate(key, default)`, which takes the type from the in-code default value. Use them where the reason matters at the point of the read, such as when reporting an evaluation to another system; the getters are enough everywhere else. Like every read, an evaluation is handed to the evaluation listeners and counted in telemetry.

<code-group>

```kotlin [MainActivity.kt]
val evaluation = client.evaluateBoolean("my-config-key", false)
if (evaluation.reason == EvaluationReason.CLIENT_NOT_READY) {
    Log.w("MyApp", "'${evaluation.key}' was read before the client was ready")
}
```

```java [MainActivity.java]
ConfigEvaluation evaluation = client.evaluateBoolean("my-config-key", false);
if (evaluation.getReason() == EvaluationReason.CLIENT_NOT_READY) {
  Log.w("MyApp", "'" + evaluation.getKey() + "' was read before the client was ready");
}
```

</code-group>

The `variation` on an evaluation is available from version 1.10.0 of the SDK, which adds the `Variation` class.

### `context`

Returns the current context (which may be `null`). When calling `updateContext`, the `context` is not immediately updated. The `context` is updated once the connection for the new context succeeds or, if it times out, once the values for the new context arrive.

### `isReady`

Returns a `Boolean` indicating if the client has been successfully initialized and is ready to evaluate configs for the given context. It is initially `false` and becomes `true` after `initialize` succeeds.
Upon calling `updateContext` it becomes `false` again and it is set to `true` once `updateContext` succeeds. It stays `false` while the client serves the [values kept on the device](#values-kept-on-the-device).

### `isInitializing`

Returns a `Boolean` indicating whether the client is trying to get its very first config state from the server. It is `false` on creation, becomes `true` when `initialize` is called on a client that has never received config state, stays `true` through timeouts and retries, and becomes `false` when the first config state arrives, when an unrecoverable connection error stops the retries, or on `close`. `updateContext` and `resumeNetwork` never set it.

To show a loading state on a slow connection rather than switching from the in-code default value to the evaluated value, end it when `initialize` returns (or calls its callback): it returns once the values arrive, and at the latest once `timeoutMillis` elapses. Don't end it when `isInitializing` turns `false`, because that can happen long after the timeout, for example when the app starts without a network.

### `pauseNetwork()` and `resumeNetwork()`

`pauseNetwork()` releases the network connection without discarding config state, watches, or listeners, and `resumeNetwork()` re-establishes it using the last context given to `initialize` or `updateContext`. Reads keep serving the last config state the client received, and `isReady` is `false` until the connection is back.

The client already does this on its own while the app is backgrounded, so these are only needed if you set `pausesWhileBackgrounded` to `false` in order to manage the connection yourself.

`resumeNetwork` has the same two forms as `initialize`: a `suspend` function for Kotlin, and one taking a `CompletionCallback`.

### `close()`

Closes the connection, every watch, and every listener registration, and reports whatever telemetry is left. The client cannot be used afterwards: it stops receiving config state and never becomes ready again, though reads keep serving the last config state it received.

Most applications never need to call it — the client lives as long as the process, and Android reclaims everything when the process ends. Call it when an application wants the client gone before that, on sign-out for instance.

## Test your code

Use the SDK's testing artifact, `com.configdirector:android-sdk-testing`, to test the code that reads your configs and flags. It creates a **test client**: the SDK's real client connected to an in-memory server that your test controls. Only the connection to ConfigDirector, the telemetry, and the app lifecycle observer are replaced. Everything else is the same code that runs in production, so the code under test behaves exactly as it does against ConfigDirector, and no network connection is opened, no telemetry is sent, no values are kept on the device, and no Android `Context` is needed. It runs in a plain JVM unit test, under Robolectric, and in an instrumented test alike.

The artifact is released together with the SDK and must be the same version as the `android-sdk` on your test classpath; `createTestClient` refuses any other. Add it in test scope:

<code-group>

```kotlin [build.gradle.kts]
dependencies {
    testImplementation("com.configdirector:android-sdk-testing:1.10.0")
    // For a Main dispatcher in plain JVM tests, see below
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
}
```

```groovy [build.gradle]
dependencies {
    testImplementation 'com.configdirector:android-sdk-testing:1.10.0'
    // For a Main dispatcher in plain JVM tests, see below
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0'
}
```

</code-group>

```kotlin [CheckoutTest.kt]
import com.configdirector.testing.createTestClient

class CheckoutTest {

    @Test
    fun `enables the new checkout when the flag is on`() = runBlocking {
        val testClient = createTestClient(values = mapOf("new-checkout" to true, "max-items" to 20))
        testClient.client.initialize()

        val checkout = Checkout(testClient.client)
        assertThat(checkout.isNewCheckoutEnabled).isTrue()

        testClient.setValue("new-checkout", false)
        assertThat(checkout.isNewCheckoutEnabled).isFalse()

        testClient.client.close()
    }
}
```

`testClient.client` is a `ConfigDirectorClient`, so it goes anywhere your code accepts one. It starts uninitialized, like a production client, because the code under test usually owns the call to `initialize`; with nothing held or failed, `initialize` completes at once with the client ready. Close it when the test is done, as your production code would.

From Java, the factory is `ConfigDirectorTesting.createTestClient(values)`, with overloads that also take the timeout and the logger. The callback overloads of the client complete on the Main dispatcher, so a plain JVM test sets one first (see below):

```java [CheckoutTest.java]
import com.configdirector.testing.ConfigDirectorTesting;
import com.configdirector.testing.TestClient;

TestClient testClient = ConfigDirectorTesting.createTestClient(Collections.singletonMap("new-checkout", true));
CountDownLatch initialized = new CountDownLatch(1);
testClient.getClient().initialize(null, initialized::countDown);
initialized.await(5, TimeUnit.SECONDS);

Checkout checkout = new Checkout(testClient.getClient());
assertThat(checkout.isNewCheckoutEnabled()).isTrue();

testClient.setValue("new-checkout", false);
assertThat(checkout.isNewCheckoutEnabled()).isFalse();

testClient.getClient().close();
```

### The Main dispatcher

The client hands listeners, watches, the `values` and `events` flows, the Compose bindings, and the Java callback overloads back on the Main dispatcher. Robolectric and instrumented tests have one. A plain JVM test does not, so it sets one from `kotlinx-coroutines-test`. With `UnconfinedTestDispatcher`, watches and listeners run inline, so a watch has seen a `setValue` by the time it returns:

```kotlin
@Before
fun setUpMainDispatcher() {
    Dispatchers.setMain(UnconfinedTestDispatcher())
}

@After
fun tearDown() {
    testClient.client.close()
    Dispatchers.resetMain()
}
```

From Java, call `TestDispatchers.setMain(Dispatchers.INSTANCE, Dispatchers.getDefault())` before the test and `TestDispatchers.resetMain(Dispatchers.INSTANCE)` after it. Reads through `getBoolean` and the other getters need no Main dispatcher. Without one, the first client call that needs it, such as registering a watch or `initialize`, fails with an `IllegalStateException` saying that `Dispatchers.Main` is missing.

### In Jetpack Compose

A composable needs a composition to run in, which on the JVM means Robolectric with `createComposeRule`, or an instrumented test. Wrap the content in the production `ConfigDirectorProvider` with the test client's client, as the app does. The client hands values to the bindings on the main looper, which Robolectric only runs when the test lets it, so idle it after `initialize` and after every change:

```kotlin [HomeScreenTest.kt]
import com.configdirector.compose.ConfigDirectorProvider
import com.configdirector.testing.createTestClient

@RunWith(RobolectricTestRunner::class)
class HomeScreenTest {

    @get:Rule
    val compose = createComposeRule()

    private val testClient = createTestClient(values = mapOf("greeting" to "hello"))

    @After
    fun tearDown() = testClient.client.close()

    private fun settle() {
        shadowOf(Looper.getMainLooper()).idle()
        compose.waitForIdle()
    }

    @Test
    fun `shows the greeting from the config`() {
        compose.setContent { ConfigDirectorProvider(testClient.client) { HomeScreen() } }
        runBlocking { testClient.client.initialize() }
        settle()
        compose.onNodeWithText("hello").assertIsDisplayed()

        testClient.setValue("greeting", "hi")
        settle()
        compose.onNodeWithText("hi").assertIsDisplayed()
    }
}
```

### Values

`values`, `setValue`, and `replaceValues` take native values, and the config type follows from each value's type: a `Boolean`; an `Int` or `Long` (an integer config); a `Float` or `Double` (a float config); a `String`; or a `Map` with `String` keys or a `List` (a JSON config). A `String` is always a string config, so JSON text meant as a JSON config is given as a `Map` or a `List`. Every value is served to every context; a test that needs different values per context is written as one test per value. A blank key, a non-finite number, a value of any other type, a `Map` with a non-`String` key, or JSON contents of any other type throw a `ConfigDirectorValidationException`, and nothing changes. From Java, a `null` value is a `NullPointerException`.

Reads behave as they do in production: `setValue("k", true)` read as a `String` returns the in-code default value with the `TYPE_MISMATCH` reason, `setValue("k", 2.5)` read with `getInt` returns `2`, a `Long` beyond the `Int` range reads through `getDouble` and gives `getInt` the `INVALID_NUMBER` reason, and `setValue("k", "")` serves the in-code default value with the `VALUE_MISSING` reason. A JSON object is encoded in the insertion order of a `LinkedHashMap`, which is what `mapOf` builds, and with sorted keys for any other map; `getJsonObject` returns it in `org.json`'s order, as in production. JSON configs parse through `org.json`, which the artifact brings for plain JVM tests, where Android's own is a stub; on a device Android's own is used.

### Controls

<table>
<thead>
  <tr>
    <th>
      Control
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        setValue(key, value)
      </code>
    </td>
    
    <td>
      Stores the value and, once the client is connected, delivers an update carrying only <code>
        key
      </code>
      
      . Reads see it when <code>
        setValue
      </code>
      
       returns; watches of <code>
        key
      </code>
      
       and <code>
        ConfigsUpdated
      </code>
      
       listeners see it once the Main dispatcher runs them.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        removeValue(key)
      </code>
    </td>
    
    <td>
      Removes the value and delivers a full update without it. Reads return the in-code default value with the <code>
        CONFIG_STATE_MISSING
      </code>
      
       reason, watches of <code>
        key
      </code>
      
       are handed the default, and <code>
        ConfigsUpdated
      </code>
      
       lists <code>
        key
      </code>
      
       in <code>
        removedKeys
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        replaceValues(values)
      </code>
    </td>
    
    <td>
      Replaces every stored value, disarms any armed hold or failure, and delivers a full update. Use it to reset a test client shared across tests.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        holdInitialization()
      </code>
    </td>
    
    <td>
      The next <code>
        initialize
      </code>
      
       waits until <code>
        completeInitialization()
      </code>
      
       or <code>
        failInitialization()
      </code>
      
      , or until the client's <code>
        timeoutMillis
      </code>
      
       elapses.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        completeInitialization()
      </code>
    </td>
    
    <td>
      Delivers the stored values to the held <code>
        initialize
      </code>
      
      , so the client is ready when it returns, and lets <code>
        initialize
      </code>
      
       complete. Called while a hold is armed but not picked up, it disarms the hold.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        failInitialization()
      </code>
    </td>
    
    <td>
      Fails the held <code>
        initialize
      </code>
      
       the way an invalid SDK key does: it completes promptly, the client is not ready, and an error is logged. Called with no <code>
        initialize
      </code>
      
       held, it arms the next one to fail.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        holdContextUpdate()
      </code>
      
      , <code>
        completeContextUpdate()
      </code>
      
      , <code>
        failContextUpdate()
      </code>
    </td>
    
    <td>
      The same for the next <code>
        updateContext
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        contextUpdates
      </code>
    </td>
    
    <td>
      The context of every <code>
        initialize
      </code>
      
       and <code>
        updateContext
      </code>
      
       call, in order. <code>
        initialize
      </code>
      
       without a context records an empty context, and <code>
        resumeNetwork
      </code>
      
       is not recorded.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        trackedEvents
      </code>
    </td>
    
    <td>
      The events the code under test tracked with <code>
        track
      </code>
      
      , in call order, each as a <code>
        TrackedEvent
      </code>
      
       with its <code>
        name
      </code>
      
      , <code>
        context
      </code>
      
      , <code>
        value
      </code>
      
       and <code>
        details
      </code>
      
      , which compare by value. An event whose name the SDK would not report is not recorded, and a value or details the SDK would leave out are missing from the record. A date in the details is recorded as the ISO 8601 text the SDK sends. The limit of 1,000 events per telemetry report does not apply to the record. It stays one list for the life of the test client and <code>
        replaceValues
      </code>
      
       leaves it alone, so a test client shared across tests clears it with <code>
        trackedEvents.clear()
      </code>
      
      .
    </td>
  </tr>
</tbody>
</table>

The initialization controls act only on `initialize` and the context update controls only on `updateContext`; `resumeNetwork` is never held or failed. After a failed attempt, the next attempt succeeds and delivers the values stored in the meantime. A held `initialize` suspends its caller, so a test that acts while it is held starts it on another dispatcher, or uses the callback overload:

```kotlin [LoadingTest.kt]
val testClient = createTestClient(values = mapOf("new-checkout" to true), timeoutMillis = 500)
testClient.holdInitialization()

val initialization = launch(Dispatchers.Default) { testClient.client.initialize() }
assertThat(testClient.client.isReady).isFalse()

testClient.completeInitialization()
initialization.join()
assertThat(testClient.client.isReady).isTrue()
```

### Options

`createTestClient` takes `values`, `timeoutMillis` (the client's connection timeout, which bounds how long a held attempt waits; defaults to the SDK's production timeout of 3 seconds), and `logger`. The logger defaults to a `StandardErrorLogger`, which writes warnings and errors to standard error, because the SDK's default `AndroidLogger` writes to logcat, which a plain JVM test does not have; pass `StandardErrorLogger(LogLevel.DEBUG)` to see everything, or any `ConfigDirectorLogger` of your own. Since the test client sends no telemetry, every tracked event that is not recorded as it was tracked logs a warning, rather than each cause once per telemetry report.

### What to expect

- Under the test client, `initialize` publishes `Ready`, then `ConfigsUpdated`, then `ContextUpdated`.
- A held attempt that times out, or that is interrupted by `pauseNetwork`, `close`, or a new attempt, leaves the client not ready until the next attempt and logs "An error occurred during initialization" (or "during context update") at error level, as production does after a connection timeout. `isInitializing` stays `true` until values arrive, as in production, unless `close` ended the attempt.
- Watches are called on registration and then only when the evaluated value changes, as in production, so a `setValue` to the value already served calls no watch, while `ConfigsUpdated` still fires.
- `pausesWhileBackgrounded` has no effect: the test client does not follow the app lifecycle, so backgrounding the app under Robolectric does not pause the connection. Call `pauseNetwork` and `resumeNetwork` to test that path; values set while paused are delivered on resume.
- After `close`, the test client's controls are silent no-ops, `track` records nothing, and no thread or coroutine from the SDK is left running.


## Sitemap

See the full [sitemap](https://docs.configdirector.com/sitemap.md) for all pages.
