LiftCanary

SDKs

Android (Kotlin)

Kotlin SDK for Android: lifecycle-aware, offline storage and a StateFlow for Jetpack Compose.

liftcanary-android decides flags on the device from a datafile that is cached and refreshed in the background, so decisions are instant, work offline and give a user the same variation as on your website, in your iOS app and on your servers. It follows the app lifecycle by itself and exposes a StateFlow for Jetpack Compose.

Install#

app/build.gradle.kts
dependencies {
    implementation("com.liftcanary:liftcanary-android:0.1.0")
}

From Maven Central; minSdk 21. The library adds the INTERNET permission and needs no ProGuard or R8 rules. The engine and client are also published without Android as com.liftcanary:liftcanary-core, plain Kotlin/JVM with no dependencies.

Set up the client#

App.kt
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        LiftCanary.init(this, "pk_live_...")
    }
}

Call init once, in Application.onCreate; LiftCanary.client returns the client anywhere after that. It starts downloading the datafile right away, keeps the datafile, unsent events and the anonymous id in SharedPreferences, logs warnings to Logcat and follows the app lifecycle through ProcessLifecycleOwner. Until the first datafile is loaded every flag is off with reason NOT_READY; to hold a splash screen:

Kotlin
lifecycleScope.launch { LiftCanary.client.awaitReady(timeoutMs = 2_000); showHome() } // suspends, off the main thread

awaitReady returns true once a datafile is available, or false after the timeout (3 seconds by default); a slow or failed download falls back to the datafile saved by an earlier run. client.onReady { ready -> } is the callback form (called on a background thread, handy from Java), and client.ready(timeoutMs) blocks, so never call it on the main thread.

Flags, variables and events#

Kotlin
val user = LiftCanary.client.createUser(
    id = LiftCanary.getAnonymousId(context),           // or your signed-in user id
    attributes = mapOf("platform" to "android", "app_version" to BuildConfig.VERSION_NAME, "plan" to "pro"),
)

if (user.isEnabled("new_checkout")) showNewCheckout()
val buttonText = user.getString("new_checkout", "button_text", "Buy now")
val steps = user.getInt("new_checkout", "steps", 3)

user.track("purchase", value = 49.90, properties = mapOf("currency" to "EUR"))
isEnabled(flagKey)
Boolean
Whether the flag is on.
getVariable(flagKey, name, fallback)
T
The variable, or the fallback when the flag or variable is missing, null or another JSON kind. Numbers come back as the fallback's type.
getString / getBoolean / getInt / getLong / getDouble
typed
The same with a typed fallback. getJson(flagKey, name) returns a parsed Map or List, or null.
decide(flagKey, sendExposure = true)
Decision
flagKey, enabled, variationKey, ruleKey, inExperiment, reason, variables, revision.
decideAll(sendExposure = true)
Map<String, Decision>
Every flag in the datafile.
logExposure(decision)
Unit
Logs the exposure of a decision made with sendExposure = false.
track(eventKey, value, properties)
Unit
A goal event, with an optional numeric value and properties.

Decisions are synchronous, thread-safe and never wait for the network. Experiment exposures are logged once per user, flag, rule and variation. Nothing the SDK does in the background throws into the app; problems are logged.

Jetpack Compose#

client.revisionFlow is a StateFlow<Int> of the datafile revision (-1 until one is loaded). It changes when a newer datafile arrives, which is the only time decisions can change. The library has no Compose dependency; a few lines in your app are enough:

Kotlin
@Composable
fun rememberDecision(user: UserContext, flagKey: String): Decision {
    val revision by LiftCanary.client.revisionFlow.collectAsState()
    // Decide without side effects while composing; log the exposure once it's shown.
    val decision = remember(user, flagKey, revision) { user.decide(flagKey, sendExposure = false) }
    LaunchedEffect(decision) { user.logExposure(decision) }
    return decision
}

@Composable
fun rememberFlag(user: UserContext, flagKey: String): Boolean = rememberDecision(user, flagKey).enabled

@Composable
fun Paywall(user: UserContext) {
    if (rememberFlag(user, "paywall_trial")) TrialBanner()
}

Open screens recompose when a newer datafile arrives, so a kill switch reaches them without a restart. Outside Compose, collect the same flow or use client.subscribe { revision -> }; client.onExposure { exposure -> } forwards exposures to your analytics.

Anonymous users and signing in#

LiftCanary.getAnonymousId(context) is a random UUID created on first use and kept in SharedPreferences under liftcanary:anonymous_id, so it lasts for the installation. Use it as the user id until the person signs in. Then create the user with your id and pass the anonymous id as anonymousId: the SDK sends one identify event, so results count the visits before and after sign-in as one person.

Kotlin
val user = LiftCanary.client.createUser(id = account.id, anonymousId = LiftCanary.getAnonymousId(context))

Switching ids can change the variation; to keep the one they had while anonymous, also pass the anonymous id as bucketingId. See From landing page to app.

Offline and the app lifecycle#

  • The datafile is downloaded at start, then every 60 seconds while the app is visible and again when it returns to the foreground (with If-None-Match, so no change costs a 304). Only a newer revision replaces the current one. An app started in the background (a push, a job) doesn't poll until it is shown.
  • The last datafile is saved in SharedPreferences. The network is still tried first, so a kill switch always wins; the saved one is used when the app starts offline or the download takes longer than ready() waits.
  • Exposures, track and identify events are queued (at most 1000) and sent in batches, and going to the background sends what's queued. The newest 200 unsent events are saved and sent on the next start.
  • Server errors, 429 and network errors are retried with backoff from 1 s to 60 s, honouring Retry-After; other 4xx answers drop the batch.
  • LiftCanary.init(context, sdkKey, observeLifecycle = false) turns lifecycle handling off; then call client.onForeground() and client.onBackground() yourself. client.close() stops the client.

On the very first launch there is nothing saved, so without network flags are off until a datafile arrives. To decide immediately even then, ship a datafile in your assets and pass it as datafile:

Kotlin
LiftCanary.init(this, "pk_live_...") {
    datafile = Datafile.parse(assets.open("liftcanary.json").bufferedReader().readText())
}

Options#

Set them in the block passed to init, as above. From Java, change LiftCanary.defaultOptions(context) and pass it to LiftCanary.init(context, sdkKey, options).

datafile
none
A Datafile to start from (bundled, for an offline first start).
cdnUrl
https://cdn.liftcanary.com
Where datafiles are served: {cdnUrl}/datafiles/{sdkKey}.json. Your own domain or a self-hosted LiftCanary.
eventsUrl
https://events.liftcanary.com
The collector: {eventsUrl}/v1/batch.
pollingIntervalMs
60000
Datafile checks while the app is in the foreground; 0 turns polling off.
eventBatchSize
20
Events per request; a full batch is sent right away.
eventFlushIntervalMs
5000
How often queued events are sent.
eventMaxQueueSize
1000
Events kept in memory before the oldest are dropped.
storage
SharedPreferences
The liftcanary preferences file. MemoryStorage() keeps nothing on disk.
cacheDatafile
true
Keep the last datafile for offline starts.
transport
UrlConnectionTransport()
Your own HttpTransport (OkHttp, a proxy, tests).
scheduler
two daemon threads
Where background work runs.
logger
AndroidLogger()
Warnings to Logcat. Logger.NONE for silence, AndroidLogger(debug = true) for more.
autoStart
true
Otherwise call client.start().