Analytics for Kotlin Migration Guide
Analytics-Kotlin is in pubic beta and currently supports these destinations with Segment actively adding more to the list. Segment’s First-Access and Beta terms govern this library.
If you’re using a different library such as Analytics-Android, follow these steps to migrate to the Analytics-Kotlin library:
You can continue to use your Android source write key for the migration to view historical events.
- Create a Kotlin Source in Segment.
- Go to Connections > Sources > Add Source.
- Search for Kotlin and click Add source.
- NOTE: You can choose between Kotlin (Android) Mobile or Kotlin Server. Kotlin Server doesn’t support device-mode destinations.
-
Replace your dependencies.
Segment recommends you to install the library with a build system like Gradle, as it simplifies the process of upgrading versions and adding integrations. The library is distributed via Jitpack. Add the analytics module to your build.gradle.
Before example:dependencies { implementation 'com.segment.analytics.android:analytics:4.+' }
After example:repositories { maven { url 'https://jitpack.io' } } dependencies { implementation 'com.github.segmentio.analytics-kotlin:android:+' }
-
Modify your initialized instance.
Before example:Analytics analytics = new Analytics.Builder(context, "YOUR_WRITE_KEY") .trackApplicationLifecycleEvents() .build();
After example:Analytics("YOUR_WRITE_KEY", context) { analyticsScope = applicationCoroutineScope trackApplicationLifecycleEvents = true }
-
Add a middleware.
Middlewares are a powerful mechanism that can augment the events collected by the SDK. A middleware is a function that the Segment SDK invokes and can be used to monitor, modify, augment or reject events.
As middlewares have the same function as enrichment plugins, you need to write an enrichment plugin to add a middleware.
Before example:builder .useSourceMiddleware(new Middleware() { @Override public void intercept(Chain chain) { // Get the payload. BasePayload payload = chain.payload(); // Set the device year class on the context object. int year = YearClass.get(getApplicationContext()); Map<String, Object> context = new LinkedHashMap<>(payload.context()); context.put("device_year_class", year); // Build our new payload. BasePayload newPayload = payload.toBuilder() .context(context) .build(); // Continue with the new payload. chain.proceed(newPayload); } })
After example:analytics.add(object: Plugin { override lateinit var analytics: Analytics override val type = Plugin.Type.Enrichment override fun execute(event: BaseEvent): BaseEvent? { // Set the device year class on the context object. int year = YearClass.get(getApplicationContext()); Map<String, Object> context = new LinkedHashMap<>(payload.context()); event.context = buildJsonObject { putAll(event.context) put("device_year_class", year) } return event } })
-
Add a destination middleware.
If you don’t need to transform all of your Segment calls, and only want to transform the calls going to specific destinations, use Destination middleware instead of Source middleware. Destination middleware is available for device-mode destinations only.
Before example:builder .useDestinationMiddleware("Segment.io", new Middleware() { @Override public void intercept(Chain chain) { // Get the payload. BasePayload payload = chain.payload(); // Set the device year class on the context object. int year = YearClass.get(getApplicationContext()); Map<String, Object> context = new LinkedHashMap<>(payload.context()); context.put("device_year_class", year); // Build our new payload. BasePayload newPayload = payload.toBuilder() .context(context) .build(); // Continue with the new payload. chain.proceed(newPayload); } })
After example:val segmentDestination: DestinationPlugin = analytics.find(SegmentDestination::class) segmentDestination.add(object: Plugin { override lateinit var analytics: Analytics override val type = Plugin.Type.Enrichment override fun execute(event: BaseEvent): BaseEvent? { // Set the device year class on the context object. int year = YearClass.get(getApplicationContext()); Map<String, Object> context = new LinkedHashMap<>(payload.context()); event.context = buildJsonObject { putAll(event.context) put("device_year_class", year) } return event } })
-
Set your config options.
Segment changed these config options:Before After collectDeviceId
Name changed to collectDeviceId
context
Name changed to application
defaultApiHost
Name changed to apiHost
defaultProjectSettings
Name changed to defaultSettings
experimentalUseNewLifecycleMethods
Name changed to useLifecycleObserver
Note: Used in tandem withtrackApplicationLifecycleEvents
flushInterval
Name changed to flushInterval
flushQueueSize
Name changed to flushAt
Segment added this option:Option Details autoAddSegmentDestination
The analytics client automatically adds the Segment Destination. Set this to false
, if you want to customize the initialization of the Segment Destination, such as, add destination middleware).
Segment deprecated these options:Option Details defaultOptions
Deprecated in favor of a plugin that adds the default data to the event payloads. Segment doesn’t provide a plugin example since it’s dependent on your needs. recordScreenViews
Deprecated in favor of the AndroidRecordScreenPlugin
that provides the same functionality.trackAttributionData
This feature no longer exists. -
Add a destination.
Segment previously used Factories to initialize destinations. With Analytics Kotlin, Segment treats destinations similar to plugins and simplifies the process in adding them.
Before example:// Previously we used to use Factories to initialize destinations analytics.use(FooIntegration.FACTORY)
After example:// Now destinations are treated similar to plugins and thus are simpler to add val destination = /* initialize your desired destination */ analytics.add(destination)
- Modify your tracking methods for Identify, Track, Group, Screen, and Alias.
-
Identify
Before example:analytics.identify("a user's id", new Traits().putName("John Doe"), null);
After example:// The newer APIs promote the use of strongly typed structures to keep codebases legible @Serializable data class UserTraits( var firstName: String, var lastName: String ) analytics.identify("a user's id", UserTraits(firstName = "John", lastName = "Doe"))
-
Track
Before example:analytics.track("Product Viewed", new Properties().putValue("name", "Moto 360"));
After example:// The newer APIs promote the use of strongly typed structures to keep codebases legible @Serializable data class ProductViewedProperties( var productName: String, var brand: String, var category: String, var price: Double, var currency: String ) analytics.track( "Product Viewed", ProductViewedProperties( productName = "Moto 360", brand = "Motorola", category = "smart watch", price = 300.00 currency = "USD" ) )
- Group
Before example:analytics.group("a user's id", "a group id", new Traits().putEmployees(20));
After example:@Serializable data class GroupTraits( var employeeCount: Int ) analytics.group("a group id", GroupTraits(employeeCount = 20))
- Screen
Before example:analytics.screen("Feed", new Properties().putValue("Feed Length", "26"));
After example:@Serializable data class FeedScreenProperties( @SerialName("Feed Length") var feedLength: Int ) analytics.screen("Feed", FeedScreenProperties(feedLength = 26))
-
Alias
Before example:analytics.alias("new id");
After example:analytics.alias("new id")
-
This page was last modified: 08 Jan 2022
Need support?
Questions? Problems? Need more info? Contact Segment Support for assistance!