Skip to content

Instantly share code, notes, and snippets.

@AdamMc331
Created February 17, 2022 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamMc331/7a0ba1840a151a32ac7f8dfed581af0e to your computer and use it in GitHub Desktop.
Save AdamMc331/7a0ba1840a151a32ac7f8dfed581af0e to your computer and use it in GitHub Desktop.
Demonstrating my approach to analytics tracking.
/**
* Interface defining the contract of any event that can be tracked in the app. It includes a unique key identifying the event,
* and ability to record properties.
*/
interface AnalyticsEvent {
val eventName: String
val properties: Map<String, Any>
}
/**
* Defines the contract of the behavior of any system that tracks events within our application.
*/
interface AnalyticsTracker {
fun trackEvent(event: AnalyticsEvent)
}
/**
* Some events can be expressed as Kotlin objects, because there's nothing dynamic about them. This is usually used for
* page views.
*/
object ViewedProfileScreenEvent : AnalyticsEvent {
override val eventName: String = "viewed_profile"
override val properties: Map<String, Any> = emptyMap()
}
/**
* Some events can be expressed as data classes, because they can have dynamic properties like the source of the page
* the user clicked on a button.
*/
data class ClickedAccountButtonEvent(
private val source: String,
) : AnalyticsEvent {
override val eventName: String = "clicked_account_button"
override val properties: Map<String, Any> = mapOf(
"source" to source,
)
/**
* The concrete implementation takes the other details & maps them to the relevant setup for whatever analytics tool
* our app uses.
*/
class SegmentAnalyticsTracker(
private val segmentInstance: Analytics,
) : AnalyticsTracker {
override fun trackEvent(analyticsEvent: AnalyticsEvent) {
val segmentProperties = Properties()
analyticsEvent.properties.forEach { (key, property) ->
segmentProperties[key] = property
}
segmentInstance.track(analyticsEvent.eventName, segmentProperties)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment