Datablit Kotlin SDK

A lightweight analytics library for Android applications to track user events and behavior. The SDK provides comprehensive functionality for event tracking, user identification, rule evaluation, and experiment variant retrieval.

Installation

Add the dependency to your build.gradle.kts:

kotlin
dependencies {
    implementation("com.datablit:kotlin:1.0.0")
}

Quick Start

Here's how to get started with the Datablit Kotlin SDK:

kotlin
import com.datablit.Datablit

// Initialize the SDK
val datablit = Datablit("your-api-key", context)

// Track an event
datablit.track("Button Click")

// Track an event with properties
datablit.track("Purchase", mapOf(
    "productId" to "123",
    "price" to 29.99,
    "currency" to "USD"
))

// Identify a user
datablit.identify("user123", mapOf(
    "name" to "John Doe",
    "email" to "john@example.com",
    "plan" to "premium"
))

API Reference

Datablit(apiKey, context, config)

Initializes the Datablit SDK. You should initialize this library once before using any other functions.

Parameters:

ParameterTypeRequiredDescription
apiKeyStringYesYour Datablit API key. Get this from the Datablit project source
Create new project/source if its not created yet
contextContextYesAndroid application context
config.endpointStringNoAPI endpoint for sending events. Default: https://event.datablit.com/v1/batch
config.flushAtIntNoNumber of events to batch before sending. Default: 20
config.flushIntervalLongNoInterval in milliseconds to flush events. Default: 30000
config.trackApplicationLifecycleEventsBooleanNoAutomatically track app lifecycle events. Default: false
config.enableDebugLogsBooleanNoEnable debug logging. Default: false

Analytics API

datablit.track(eventName, properties)

Tracks an event with associated properties.

Parameters:

ParameterTypeRequiredDescription
eventNameStringYesName of the event.
propertiesMap<String, Any>NoKey-value pairs of event properties.

Example:

kotlin
datablit.track("Button Click")

// Track with properties
datablit.track("Purchase", mapOf(
    "productId" to "123",
    "price" to 29.99,
    "currency" to "USD"
))

datablit.identify(userId, traits)

Identify a user with a unique ID and optional traits.

Parameters:

ParameterTypeRequiredDescription
userIdStringYesUnique user ID.
traitsMap<String, Any>NoAdditional user attributes.

Example:

kotlin
datablit.identify("user123", mapOf(
    "name" to "John Doe",
    "email" to "john@example.com",
    "plan" to "premium"
))

datablit.flush()

Manually flush queued events to the server.

Example:

kotlin
datablit.flush()

Rules API

datablit.rule.evalRule(request, callback)

Evaluates a rule for a given user and context. This allows you to make dynamic decisions based on user attributes and rule logic.

Parameters:

ParameterTypeRequiredDescription
keyStringYesThe rule key identifier.
userIdStringYesUnique user ID.
paramsMap<String, Any>NoAdditional parameters for rule evaluation.
callbackFunctionYesCallback function to handle the result.

Example:

kotlin
datablit.rule.evalRule(
    key = "feature_flag",
    userId = "user123",
    params = mapOf(
        "os_name" to "android",
        "app_version" to "1.0.0"
    )
) { result ->
    result.onSuccess { ruleResult ->
        if (ruleResult.result) {
            println("Rule evaluated to true")
        } else {
            println("Rule evaluated to false")
        }
    }.onFailure { error ->
        println("Rule evaluation failed: ${error.message}")
    }
}

Experiments API

datablit.experiment.getVariant(request, callback)

Retrieves the experiment variant for a user. This is useful for A/B testing and feature experimentation.

Parameters:

ParameterTypeRequiredDescription
expIdStringYesThe experiment ID.
entityIdStringYesUnique entity/user ID.
callbackFunctionYesCallback function to handle the result.

Example:

kotlin
datablit.experiment.getVariant(
    expId = "01K2JKVXR0J0ZWPX40XY8CAWBS",
    entityId = "user123"
) { result ->
    result.onSuccess { response ->
        println("User is in variant: ${response.variant}") // "control", "variant_a", etc.

        // Use the variant to show different UI
        when (response.variant) {
            "variant_a" -> {
                // Show new feature
            }
            else -> {
                // Show control version
            }
        }
    }.onFailure { error ->
        println("Failed to get variant: ${error.message}")
    }
}

Auto-Tracked Events

Application Lifecycle Events

If trackApplicationLifecycleEvents is set to true, the SDK will automatically track the following events:

  • Application Opened
  • Application Backgrounded
  • Application Foregrounded

These events include contextual information such as device details, OS version, screen dimensions, locale, timezone, and more.

Error Handling

The SDK provides comprehensive error handling mechanisms through Result objects:

kotlin
// Rule evaluation with error handling
datablit.rule.evalRule(
    key = "feature_flag",
    userId = "user123"
) { result ->
    result.onSuccess { ruleResult ->
        // Handle successful rule evaluation
        println("Rule result: ${ruleResult.result}")
    }.onFailure { error ->
        // Handle error
        println("Rule evaluation failed: ${error.message}")
    }
}

// Experiment variant with error handling
datablit.experiment.getVariant(
    expId = "01K2JKVXR0J0ZWPX40XY8CAWBS",
    entityId = "user123"
) { result ->
    result.onSuccess { response ->
        // Handle successful variant retrieval
        println("Variant: ${response.variant}")
    }.onFailure { error ->
        // Handle error
        println("Failed to get variant: ${error.message}")
    }
}

Features

  • Event Tracking: Track custom events with properties
  • User Identification: Identify users with traits
  • Automatic Batching: Events are automatically batched and sent to the server
  • Offline Support: Events are queued locally and sent when network is available
  • Lifecycle Tracking: Optional automatic tracking of application lifecycle events
  • Rule Evaluation: Evaluate feature flags and rules for users with context parameters
  • Experiment Variants: Get experiment variants for users
  • Configurable: Customize flush intervals, batch sizes, and endpoints

Permissions

Ensure that the following permissions are declared in your AndroidManifest.xml:

xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Note: Always adhere to Android's permission guidelines and request runtime permissions when necessary.

For more information, examples, and contributions, visit the Datablit Kotlin SDK GitHub repository.