Analytics¶
The Starter Template provides a modular, provider-agnostic analytics system built with Clean Architecture. You can track events, purchases, user behavior, and more while keeping your implementation flexible.
Setup¶
- Open the constants file:
| composeApp/src/commonMain/.../core/AppConstants.kt | |
|---|---|
- Replace
"add-your-mixpanel-token-here"with your Mixpanel project token.
Info
See the official Mixpanel docs for generating your token.
1. Define Event Keys¶
1: Inside the companion object, define your event key:
| features/analytics/domain/.../AppEventsTracker.kt | |
|---|---|
2: Add a corresponding track function in the interface:
| features/analytics/domain/.../AppEventsTracker.kt | |
|---|---|
Note
- Use descriptive function names starting with
track. - Keep keys consistent and unique across the app.
Full Example
features/analytics/domain/.../AppEventsTracker.kt
interface AppEventsTracker {
// events names
companion object {
const val KEY_ONBOARDING_TRAFFIC_SOURCE = "traffic_source"
const val KEY_PURCHASE_SUCCESS = "purchase_success"
const val KEY_PURCHASE_FAILURE = "purchase_failure"
const val KEY_PURCHASE_RESTORE_FAILURE = "purchase_restore_failure"
const val KEY_PURCHASE_PRODUCTS_FAILURE = "purchase_products_failure"
}
// onboarding
suspend fun trackTrafficSource(source: String)
// purchases
suspend fun trackPurchaseSuccess(productId: String)
suspend fun trackPurchaseFailure(productId: String, error: String)
suspend fun trackPurchaseProductsFailure(error: String)
suspend fun trackPurchaseRestoreFailure(error: String)
}
2. Implement the Event¶
Implement the new function using the existing EventsTracker:
| features/analytics/data/.../AppEventsTrackerImpl.kt | |
|---|---|
Full Example
3. Use in ViewModel¶
| SignInViewModel.kt | |
|---|---|
Note
- Keep the analytics calling inside presentation layer
- Best place is viewModel
Replacing Analytics Provider¶
-
To swap Mixpanel with another provider:
-
Implement the
EventsTrackerinterface in the data layer. - Update your Koin module to provide your implementation.
Note
- Domain layer, ViewModels, and Compose code remain unchanged.
- This allows switching providers without rewriting app logic.