API reference
Android SDK v1.4.0 — API reference
Everything is reachable from the Optima singleton once you've called
Optima.init(context, config) (chapter 1):
val optima = Optima.instance // throws if init hasn't run yetOptima.track(...) and Optima.screen(...) also exist as static
conveniences that read the singleton internally; calling them before init
logs one warning (Optima used before init; call dropped) and is otherwise a
silent no-op, never a crash.
Every public entry point is guarded. An internal failure — a thrown
exception anywhere inside the SDK's own code — becomes an Error(op, cause)
event (see Events) plus a debug log line; it is never rethrown
into your app. identify(...) and consent.set(...) are the two calls
where you might want to know the outcome of the first network attempt
rather than just observe events, so they hand you a Job (identify) or are
themselves suspend (consent.set) — everything else fires-and-forgets by
design.
Threading. The SDK owns one CoroutineScope(SupervisorJob() + Dispatchers.IO) for all of its own work. Every public method returns
immediately — nothing blocks the calling thread, including the calling main
thread. Listeners (addListener, events) are always dispatched on the main
thread, so it's safe to touch UI directly from inside a listener callback.
Optima / OptimaClient
Optima.init(context: Context, config: OptimaConfig)
Constructs the runtime: opens/creates the SharedPreferences file, prepares
the outbox file under filesDir/optima/outbox.jsonl, reads device info
(PackageManager, Resources), registers the Activity-lifecycle observer,
and fires the Ready event. A second call is a no-op with a
Log.w("optima", "Optima.init called twice; the first configuration stays")
warning — the first configuration always wins, mirroring the Web SDK's
window.optima.__v guard. See chapter 1
for the failure-tolerant construction contract.
Optima.instance: OptimaClient
The live client — or an inert disabled client when there is no runtime,
i.e. init was never called, or its construction failed and was swallowed
(see Optima.init above). It never throws. The disabled client's methods are
no-ops, its flows are permanently empty (content.slot(...) is an empty
StateFlow, consent.get() a blank ConsentState, forms.load(...) a
FormResult.Failed, push.parse(...) null), deviceId is "", and config
echoes back whatever was passed to the failed init (a placeholder if init
was never called at all). The first access logs one warning.
That symmetry is the point: an SDK that has already decided not to crash your
Application.onCreate must not crash instead at the first call that follows —
a by lazy field, a composable, a lifecycle callback. Use isInitialized when
you need to know which client you are holding.
Optima.isInitialized: Boolean
true once init has completed successfully (or been called at all — note
that a construction failure inside init, per the try/catch above, leaves
this false and the singleton uninitialized, exactly as if init had never
been called).
track(category: String, name: String? = null, props: Map<String, Any?>? = null)
Queues one hit to the on-disk outbox. category is required, 1–128
characters (an out-of-range value throws inside the guard and surfaces as an
Error("track", ...) event rather than propagating). name and props are
both optional. Sends: the built TrackHit batches into POST /edge/v1/track
(see Hits and transport below) —
nothing is sent synchronously by this call itself. Emits: a Track event
once the containing batch is acked or rejected by the server (never one event
per track() call — see that section). Threading: non-blocking, returns
immediately; the actual HTTP call happens later, on the SDK's own scope.
screen(name: String, props: Map<String, Any?>? = null)
The Web SDK's page(), renamed for the platform: records a screen view. It
is track("screen_view", name, props) plus automatic attribution enrichment
(UTM/click-id props; the session id and session_start are stamped on every
hit, track included), and it also sets the current screen used by the content
engine's targeting (see chapter 5) and
triggers a re-fetch of every declared content slot. Called automatically for
you on every Activity resume when screenTracking = AUTO (chapter
2), using the Activity's simple class name; call it
yourself when screenTracking = OFF, or whenever your own navigation model
(Compose Navigation, a single-Activity app, a Fragment-based flow) doesn't
line up with Activity boundaries. Sends/emits/threading: identical to
track above, since it is a track call under the hood — see Hits and
transport.
captureReferrer(referrer: String)
Feeds a Play Install Referrer string
(ReferrerDetails.installReferrer, a query string such as
utm_source=google-play&utm_medium=organic) into the same attribution store
the launching deep link writes to. The recognised keys (utm_source,
utm_medium, utm_campaign, utm_term, utm_content, gclid, fbclid)
are repeated as props on every enriched hit of one session: the session
of the next hit after the capture. The newest capture wins, so a later deep
link with UTMs replaces an earlier set. A referrer string is applied once per
install, and the same string on later launches is ignored — also after
reset(). Only a SHA-256 of the referrer is kept to recognise it (the raw
string can carry click ids); reset() clears the stored attribution set.
The SDK does not depend on the Play Install Referrer library; your app adds
it and calls this once, typically on first launch. The five-line recipe is in
chapter 1. Sends nothing
by itself and emits nothing; errors are guarded into an Error("capture_referrer")
event.
identify(identifiers: Map<String, String>, attributes: Map<String, Any?>? = null, assertion: IdentityAssertion? = null): Job
Attaches allowlisted identifiers and/or profile attributes to this device.
This attaches identifiers nobody owns yet; an identifier another
customer already owns is NOT attached (it is recorded as an unverified
claim for identity rules) unless assertion — minted by your backend with
the SDK key's identify secret — proves it. A call with identifiers,
attributes and assertion all empty/null is skipped locally (logged at
debug, nothing is sent — "identify: nothing to send"). Sends: POST /edge/v1/identify with {device_id, identifiers, attributes, consent, assertion}; identifiers/attributes are
filtered server-side against the admin-configured identify_allowed_keys /
identify_allowed_attributes allowlists — anything not on the allowlist
comes back in the response's dropped array rather than failing the whole
call. Emits: Identify(accepted, dropped) on success; Error("identify", cause) after the retry ladder (5 attempts, Retry-After honoured) is
exhausted, or immediately on a terminal 4xx. Threading: returns a Job
immediately; await it if you need to know the first attempt has actually
landed (e.g. before navigating away from a login screen), but nothing
requires you to.
reset()
"A different person is using this device now" — call it on logout on any
shared/kiosk device. In order: clears the outbox, rotates the device id
(a fresh UUIDv4, _optima_did), clears consent (_optima_consent), clears
the session (_optima_sid), clears attribution (_optima_utm), clears the
content "seen" memory (_optima_seen), then runs every registered reset hook
— which includes re-content-engine-reset (all slots go empty, in-flight
fetches are fenced off by a generation counter), tracker-gate reset (the
/edge/v1/trackers inventory is discarded and re-fetched on next use), and
re-sending the remembered push token under the new device id (an
identify({push_token_fcm: <token>}) call) — because the physical device
still has that FCM registration and the new profile on it should still
receive pushes, unless you don't want that (see
chapter 7 for the setToken(null)
escape hatch). The push token itself is the one storage key reset() does
not clear. Sends/emits: nothing synchronous of its own beyond the hooks
above; no network call is required to "complete" a reset. Threading:
synchronous, non-suspend — everything it does is local state mutation plus
scheduling background work.
deviceId: String
The SDK-minted device id (_optima_did), a UUIDv4 generated once on first
use and persisted — never derived from any hardware identifier, IMEI,
Android ID, or advertising ID. Read-only from the public API; it rotates
only via reset().
suspend flush()
Forces an immediate attempt to drain the outbox, bypassing the normal 20-hit
batch size / 2-second coalesce window (though it still respects an
in-progress backoff retry — "one flush in flight at a time"). Sends: whatever
is currently queued, via the same POST /edge/v1/track path as an automatic
flush. Emits: the same Track/Error events an automatic flush would. Also
called automatically by the SDK on app background. Threading: suspend;
returns once that one flush attempt (success, terminal rejection, or a
queued retry) has run — see Tracker.flush()'s single-batch-per-call
contract if you're draining a very large outbox and need it fully empty,
in which case call it again.
addListener(listener: OptimaListener): Closeable
Registers a listener that receives every OptimaEvent from here forward,
dispatched on the main thread. OptimaListener is a fun interface
({ fun onEvent(event: OptimaEvent) }), so a lambda works:
val subscription = Optima.instance.addListener { event ->
if (event is OptimaEvent.Error) Log.w("MyApp", "optima error in ${event.op}", event.cause)
}
// later, e.g. in onDestroy():
subscription.close()Call .close() on the returned Closeable to unsubscribe — matters for
anything shorter-lived than the process, like an Activity or a Compose
DisposableEffect.
events: SharedFlow<OptimaEvent>
The same event stream as addListener, as a SharedFlow for Compose/Flow
consumers:
LaunchedEffect(Unit) {
Optima.instance.events.collect { event -> /* ... */ }
}Ready is replayed to late subscribers of both addListener and events —
a listener attached after init has already completed still sees the
Ready(version) event, so "did the SDK finish starting" never races against
listener registration order.
Hits and transport (track / screen)
Every track/screen call builds a TrackHit: a message_id (UUID), an
RFC 3339 ts, a context object (language, screen_w, screen_h, ua
in the form android/<osVersion>/<packageName>/<appVersion>/sdk-<sdkVersion>,
url in the app://<package>/<screen> form — see
chapter 5 — and title set to the current
screen name), and props (the session id, session_start on a fresh
session, attribution props on screen() calls, plus whatever you passed).
Hits queue into the append-only outbox file (filesDir/optima/outbox.jsonl,
capped at 200 entries — oldest dropped first once full) and flush as a batch:
- when 20 hits are queued,
- 2 seconds after the first hit lands in an otherwise-idle queue
(coalescing — a burst of
track()calls inside that window ships as one request), - on app background,
- or on an explicit
flush().
Only one flush is in flight at a time. Each POST /edge/v1/track request
carries device_id, sent_at, the batch of hits, and the current
consent declaration (see chapter 4 for the omit-vs-[]
rule — this is why every batch, not just the first, carries consent: the
server needs it on every write, not just at "sign-up"). A 2xx response acks
the whole batch (removes it from the outbox, emits Track); a 4xx is
terminal — the batch is still acked (removed) and an Error("track", ...)
event fires, because retrying a rejected batch forever would wedge the
outbox behind a hit the server will never accept. A 429/503/network
failure keeps the batch queued and retries on a backoff ladder — 1s → 2s →
5s → 15s → 60s, resetting to the start of the ladder on the next success,
and honouring a server-sent Retry-After header over the ladder's own step
when present.
ConsentApi (optima.consent)
See chapter 4 for the full behavioural writeup (the banner,
the omit-vs-[] rule, CMP passthrough, revocation, gating third-party SDKs).
This section is the reference.
consent.get(): ConsentState
Returns the current state synchronously, from memory (backed by
_optima_consent). ConsentState is {v, decisions, decidedAt, bannerId, policy, lang} — see Types below.
consent.changes: StateFlow<ConsentState>
The same state as a StateFlow, for reactive UI: .collectAsState() in
Compose, .collect { } elsewhere. Emits immediately on subscription with the
current value (it's a StateFlow), then again on every consent.set(...)
and on reset() (which resets to a fresh, undecided ConsentState()).
suspend consent.set(decisions: Map<String, Boolean>, meta: ConsentMeta? = null)
Records a decision. Writes locally first (so consent.get() reflects it
immediately, before any network round trip), emits ConsentChange(state),
and — for any purpose that flips from true to false relative to the
previous state — also emits ConsentRevoked(purposes). Then it POSTs
/edge/v1/consent with {device_id, consents: [{purpose, granted}, ...], consent (the vendor-level block: tcf/gcm/keys, purposes omitted), banner_id?, lang?} on the same 5-attempt retry ladder as identify
(Retry-After honoured; a final give-up emits Error("consent", cause)).
The decision is also recorded durably before the first attempt
(_optima_consent_pending, per device id). If every attempt fails, or the
process dies mid-ladder, it is replayed on the next launch, foreground or
successful track flush until Edge acknowledges it (or rejects it with a
4xx). reset() does not discard a pending decision from the previous
device id.
meta carries bannerId/lang/policy when the decision came from the
built-in banner or your own consent UI referencing a specific banner/policy
version. If beforeDecision = BUFFER and this is the first decision ever
recorded, it also unblocks the tracker's flush queue (scheduleFlush()),
since a decision now exists. Threading: suspend — await it if you need to
be sure the local write (at minimum) has happened before proceeding, e.g.
before dismissing a consent-gate screen.
consent.setKeys(keys: Map<String, Boolean>) / consent.setGCM(g: Map<String, GcmValue>) / consent.setTCF(tc: String)
Vendor-level consent signals that ride alongside — never instead of — the
purposes array (when source = OPTIMA) on every subsequent request.
setKeys sets arbitrary named boolean flags; setGCM sets Google Consent
Mode-style values (GcmValue.GRANTED/GcmValue.DENIED) keyed by GCM
parameter name (ad_storage, analytics_storage, ...); setTCF sets the
raw IAB TCF consent string. All three are synchronous, local-only calls —
they take effect on the next request built, they do not themselves trigger
a network call. Under source = OPTIMA you'd normally call these only if
you're mixing your own vendor signal with Optima-owned consent; under
source = CMP the TCF string is fed to you automatically (see next) and
these are your manual hooks for GCM/keys.
consent.can(trackerName: String): Boolean
Answers "does the current consent state permit trackerName to run", by
looking trackerName up in the once-per-session /edge/v1/trackers
inventory and checking whether its declared purpose is currently granted.
Returns false for an unknown tracker name or while the inventory hasn't
loaded yet (fail-closed — a tracker you can't confirm consent for doesn't run).
See chapter 4 for the Firebase
gating example this exists for.
ContentApi (optima.content)
See chapter 5 for the full behavioural writeup. This section is the reference.
content.slot(name: String): StateFlow<List<Presentation>>
Declares a content slot: fetches GET /edge/v1/content?slot=<name>&screen= <currentScreen>&url=app://<pkg>/<currentScreen>&device_id=<id> immediately,
and again on every subsequent screen() change, with If-None-Match caching
per slot. A response belonging to an already-superseded screen is discarded
(a per-slot generation counter fences it) — you will never see a stale
screen's items flash into a slot you're currently looking at. The returned
StateFlow updates in place as items resolve (including delayed/event-
triggered items, see chapter 5). Calling
slot(name) for a name you've already declared returns the existing flow —
it does not re-declare or re-fetch. content.declaredSlots: StateFlow<Set<String>>
tracks every name ever passed here, which is how OptimaHost (Compose,
below) discovers every slot in the app without keeping its
own registry.
suspend content.fetch(slot: String): List<ContentItem>
A one-shot fetch: same request shape as slot(...), but declares
nothing (doesn't add to declaredSlots, doesn't get re-fetched on
screen() changes) and applies no display rules, frequency capping, or
placement resolution — you get the raw ContentItem list back and decide
what to do with it yourself. This is the headless entry point; see
chapter 5. Returns an empty list on any
network/server failure (never throws; a content_fetch Error event fires
first).
content.report(item: ContentItem, action: ContentAction)
Note the parameter type in the interface is actually Presentation, not
ContentItem — ContentApi.report(presentation: Presentation, action: ContentAction). Reports feedback for an item you're displaying:
ContentAction.IMPRESSION | CLICK | DISMISS. Impressions are deduped
per (slot, item id) automatically — reporting the same item's impression
twice is a no-op the second time, until the slot's content actually changes
(a fresh fetch resets that memory). Batches (≤ 50, 1-second coalesce, also
flushed on app background) to POST /edge/v1/content/events with {token, action, ts} per event, using the item's own delivery token. Also, locally
and without waiting on the network: an IMPRESSION marks the item "shown"
for frequency-rule purposes (once/per_days rules, _optima_seen); a
DISMISS marks it "dismissed" (for ttl_days) and removes it from the
slot's flow; a CLICK on a campaign item with stop_on_click = true also
removes it from the flow.
With display.htmlMode = HtmlMode.OFF, an unstructured item never becomes a
Presentation at all — it is emitted as a ContentItem(slot, item) event
instead, so a host that renders its own HTML (or deliberately renders none) can
still see what the gateway served. It is not counted in ContentLoaded.count.
content.refresh()
Re-fetches every currently declared slot immediately, without waiting for
the next screen() change. Useful after consent.set(...) changes what
should be visible (the built-in ConsentBannerRenderer calls this itself
right after posting a decision, so a served banner_consent item stops
being returned on the very next poll).
content.register(type: String, renderer: Any)
Registers a renderer for a custom structured content type your backend
authors, so the Compose module's RenderPresentation can find it instead of
falling through to a plain ContentItem event. The parameter is Any at
this (headless) layer — the Compose module's OptimaRenderer is what you
actually pass in practice, see Compose module below.
content.rendererFor(type) reads the registry back (used internally by the
Compose renderers).
FormsApi (optima.forms)
See chapter 6 for the full writeup.
suspend forms.load(id: String, lang: String? = null, assertion: IdentityAssertion? = null): FormResult
Pass assertion (the backend-minted IdentityAssertion that identify takes) when a logged-in visitor fills the form: the bound submit sends it, and it must vouch for an identifier field the submission carries, or the gateway answers 400 invalid_assertion (Rejected).
GET /edge/v1/forms/{id}?device_id=&lang= → a sealed FormResult:
Loaded(definition, submit) on success — definition: FormDefinition (see
Types below), and a bound
submit: suspend (Map<String, Any?>) -> SubmitResult closure that already
carries the form's render nonce, so you never handle it yourself; NotFound
on a 404; Failed(status, cause) on anything else, including a network
failure. Calling the bound submit(values) does POST /edge/v1/forms/{id}/submit with the honeypot field silently included and
empty (_hp), the nonce, device_id, and your values (unsupported value
types — anything that isn't String/Boolean/Int/Long/finite
Double/Float — are dropped with a debug log, never sent). A 409
response counts as success (Accepted, the form was already submitted by
this device — not an error state to surface to the user). Emits
FormSubmitted(id, dropped, doubleOptIn) on any accepted outcome (including
the 409 case).
forms.pageUrl(url: String): String
Appends device_id=<id> (as a new query parameter, or &-joined if the URL
already has one) to a hosted form page URL, for opening in a Custom Tab —
see chapter 6.
NbaApi (optima.nba)
nba.respond(nbaId: String, action: NbaAction, extra: NbaExtra? = null)
Records a Next-Best-Action response. nbaId must be exactly 26 characters
(a ULID) — anything else is dropped locally at debug level
("nba.respond dropped: nba_id must be 26 characters") without a network
call. action is one of NbaAction.PRESENTED | ACCEPTED | POSTPONED |
REJECTED | REALIZED. extra optionally carries reason, referenceId,
value. Batches (≤ 50, 1-second coalesce, flushed on background) to POST /edge/v1/nba/responses with {events: [{nba_id, action, reason, reference_id, value, ts (seconds)}]}. A 404 response permanently
disables the queue for the rest of the process's lifetime — the operator's
kill switch (edge_nba_responses_enabled off) is treated as "NBA responses
aren't a thing right now," not a transient error, so the SDK stops trying and
drops anything already queued, logging one debug line
("nba responses are disabled by the operator (404); no further sends this process"). Restarting the process re-enables the queue on the next
respond() call, in case the operator has since flipped the switch back on.
PushApi (optima.push)
See chapter 7 for the full FCM integration recipe.
push.setToken(token: String?)
Stores the FCM registration token (_optima_push_token) and, unless Edge has
already acknowledged this exact token for this device, calls
identify({push_token_fcm: token}) to attach it to the current profile.
This background sync never emits an Error event for running out of retries
while offline (it retries on the next launch/foreground by itself); a terminal
4xx still emits Error("identify").
Passing null forgets the token locally (removes the stored value) without
sending anything — it does not send an identify clearing the server-side
value; see chapter 7 for why you'd do
this before reset(). Deduplication is against what Edge acknowledged for
this device (_optima_push_synced), not against what is stored. So calling
setToken unconditionally on every app start is cheap once the token is
registered, and a registration that failed earlier is retried: on that call,
on the next launch and on every foreground.
push.parse(extras: Map<String, String>): OptimaPush? (and a Bundle overload)
Parses an incoming FCM message's data payload into OptimaPush. Returns
null if none of the SDK's reserved keys (deep_link, buttons,
optima_open, image_url) are present — i.e. this wasn't a push the SDK's
delivery pipeline built. OptimaPush is {deepLink, buttons, data, openToken}: buttons parses the buttons JSON array into PushButton{id, label, deepLink}; data is every other extra key (your own custom data),
with the reserved keys filtered out; openToken is the raw optima_open
value (you generally don't need this directly — trackOpen below consumes
it for you). The Bundle overload (push.parse(extras: Bundle)) is a thin
wrapper for calling straight from remoteMessage.data-adjacent Android APIs
without converting to a Map yourself.
push.trackOpen(extras: Map<String, String>): Boolean (and a Bundle overload)
Call from the launched Activity's onCreate/onNewIntent — the FCM data
keys ride the launch Intent's extras for a data-only (or notification+data)
message. If optima_open is present and non-blank, fires GET /edge/v1/o/{token} fire-and-forget (on the same backoff ladder as
everything else, up to 5 attempts, failures only logged at debug — never
surfaced as an Error event, since a missed open record shouldn't disturb
the app) and returns true immediately (it does not wait for the request to
land). Returns false, doing nothing, if optima_open is absent — i.e. this
either wasn't an Optima-sent push, or the template it came from didn't have
open tracking enabled. See chapter 7 for the backend
prerequisites this token depends on.
OptimaConfig
See chapter 2 for every key's default and meaning.
Built via OptimaConfig(key, endpoint) { ... } (a top-level operator fun invoke wrapping the nested Builder), immutable once built.
Types
ConsentState
data class ConsentState(
val v: Int = 1,
val decisions: Map<String, Boolean> = emptyMap(),
val decidedAt: Long? = null,
val bannerId: String? = null,
val policy: Map<String, Any?>? = null,
val lang: String? = null,
) {
val decided: Boolean // decidedAt != null
val granted: List<String> // decisions.filterValues { it }.keys.sorted()
}Presentation / ContentItem / DisplayRule
data class Presentation(val slot: String, val item: ContentItem, val placement: DisplayRule.Placement, val dismissible: Boolean)
enum class ContentAction(val wire: String) { IMPRESSION, CLICK, DISMISS }
data class ContentItem(
val id: String, val type: String, val format: String, // format: "structured" | "unstructured"
val payload: JSONObject?, val html: String?, val priority: Int,
val origin: String?, val channel: String?, val token: String?, // origin == "campaign" for an onsite-campaign item (isCampaign)
val campaignDisplay: CampaignDisplay?,
) { val isCampaign: Boolean; val display: DisplayRule }
data class DisplayRule(
val placement: Placement?, // INLINE | OVERLAY, null lets the SDK choose (OVERLAY by default)
val position: String, // "top" | "bottom" | ...
val style: String, // "card" | "bar" | "modal" | ...
val trigger: Trigger, // on: "load" | "delay" | "event" (scroll/exit fold to "load" — no DOM on Android)
val frequency: Frequency, // Always | Session | Once | PerDays(days)
val dismissible: Boolean?,
val ttlDays: Int?,
)Full field-by-field targeting/rule semantics live in chapter 5.
FormDefinition / FormResult / SubmitResult
data class FormField(val key: String, val kind: String, val inputType: String, val label: String, val placeholder: String?, val required: Boolean, val options: List<Pair<String, String>>)
data class FormDefinition(val id: String, val slug: String, val name: String, val lang: String, val fields: List<FormField>, val successMessage: String?, val successRedirectUrl: String?, val doubleOptIn: Boolean, val minSubmitIntervalSec: Int)
sealed class FormResult {
data class Loaded(val definition: FormDefinition, val submit: suspend (Map<String, Any?>) -> SubmitResult) : FormResult()
object NotFound : FormResult()
data class Failed(val status: Int?, val cause: Throwable?) : FormResult()
}
sealed class SubmitResult {
data class Accepted(val dropped: List<String>, val doubleOptIn: Boolean) : SubmitResult()
data class Rejected(val status: Int, val message: String) : SubmitResult()
data class Failed(val cause: Throwable?) : SubmitResult()
}OptimaPush
data class PushButton(val id: String, val label: String, val deepLink: String?)
data class OptimaPush(val deepLink: String?, val buttons: List<PushButton>, val data: Map<String, String>, val openToken: String?)Events
OptimaEvent is a sealed class; names are identical to the Web SDK's where
the same concept exists.
| Event | Payload | When |
|---|---|---|
Ready | version: String | Once, right after Optima.init finishes constructing the runtime. Replayed to any listener/collector attached later. |
Track | accepted: Int, dropped: List<Map<String, String>>, hits: Int | After every acked or terminally-rejected POST /edge/v1/track batch — hits is the batch size, accepted/dropped come from (or default from) the server response. |
Identify | accepted: Int, dropped: List<Map<String, String>> | After a successful POST /edge/v1/identify. |
ConsentChange | state: ConsentState | Every time consent.set(...) completes its local write, and on reset() (with a fresh, undecided state). |
ConsentRevoked | purposes: List<String> | Alongside ConsentChange, only when at least one purpose flipped true → false. |
ContentLoaded | slot: String, count: Int | After each content fetch for a declared slot resolves — count excludes items dropped as platform-inapplicable (web_personalization) and items diverted to a plain ContentItem event instead of a presentation. |
ContentItem | slot: String, item: ContentItem | For an item that doesn't become a Presentation: an unregistered structured type, or a banner_consent item while consent.source = CMP (you're expected to route it to your own CMP UI). |
FormSubmitted | id: String, dropped: List<String>, doubleOptIn: Boolean | On any accepted form submission outcome, including the "already submitted" 409 case. |
TrackerFired | name: String, kind: String | When a pixel-kind managed tracker fires (see chapter 4 and the tracker gate). |
Error | op: String, cause: Throwable? | Any guarded operation that threw, or gave up after its retry ladder. op names the operation ("track", "identify", "consent", "forms_submit", "content_fetch", "lifecycle", etc.) so you can filter for the ones you care about. |
Compose module (optima-sdk-compose)
Everything below lives in the separate optima-sdk-compose artifact
(depends on optima-sdk); see chapter 5 for how these fit
into a full screen.
OptimaHost(client: OptimaClient = Optima.instance, theme: OptimaTheme = OptimaTheme.fromMaterial(), modifier: Modifier = Modifier)
Place once, near the root of your composition (inside your app's theme,
so OptimaTheme.fromMaterial() picks up the right colours). Draws every
OVERLAY-placement presentation from every slot ever declared anywhere in
the app (it reads client.content.declaredSlots), plus the implicit
__overlay slot the engine uses for items with no explicit slot — so you
don't need to know in advance which slots exist. Renders nothing (and costs
nothing beyond the StateFlow collection) when there's nothing to show.
OptimaSlot(name: String, client: OptimaClient = Optima.instance, theme: OptimaTheme = OptimaTheme.fromMaterial(), modifier: Modifier = Modifier)
Declares (via content.slot(name)) and renders inline-placement
presentations for one named slot, in place, wherever you put this composable
in your layout. An INLINE-placement item with no OptimaSlot for its slot
name anywhere in the composition simply never renders — see chapter
5.
OptimaRenderer / RenderActions
fun interface OptimaRenderer { @Composable fun Render(presentation: Presentation, actions: RenderActions) }
class RenderActions(val onImpression: () -> Unit, val onClick: () -> Unit, val onDismiss: () -> Unit, val openUrl: (String) -> Unit)OptimaRenderer is what content.register(type, renderer) expects for a
Compose-hosted app — implement it for your own structured content types
and register it (typically once, near Optima.init); RenderActions is
handed to every renderer (built-in or yours) and wires impression/click/
dismiss straight into content.report(...), plus openUrl for outbound
links (a Custom Tab for http(s)://, an implicit ACTION_VIEW intent
otherwise — both wrapped in runCatching so a malformed/unhandleable URL
never crashes the host).
OptimaTheme
data class OptimaTheme(val surface: Color, val onSurface: Color, val primary: Color, val onPrimary: Color, val shape: Shape) {
companion object {
@Composable fun fromMaterial(): OptimaTheme // reads the ambient MaterialTheme — the default for OptimaHost/OptimaSlot
fun default(): OptimaTheme // a fixed, non-@Composable palette for previews/tests
}
}The subset of a Material palette the built-in renderers (banner,
consent-banner, in-app card/bar/modal) style themselves with, so you don't
have to hand-tune every renderer individually — override it by passing your
own OptimaTheme to OptimaHost/OptimaSlot instead of the default.
TrackerGate (internal)
Not part of the public API, mentioned here because TrackerFired events and
consent.can(...) both depend on it: the SDK fetches GET /edge/v1/trackers once per session (ETag-cached), and for kind = "pixel"
rows, fires a GET request against the configured URL (with {{url}}/{{ts}}
substituted) once per screen view when the tracker's purpose is currently
granted and the current URL matches its url_patterns glob. script/
html/page-kind rows are intentionally inert on Android — see chapter
8.