Using KSP output in app: Part 4
Aniket Bhoite
Posted on April 11, 2022
Now that we have our generated class, Let's try to use it in code.
Checkout other parts in this series:
First let's look at what is Event Interface and what methods it contains.
package com.aniket.myevent
import android.os.Bundle
interface Event {
fun getHashMapOfParamsForCustomAnalytics(): HashMap<*, *>?
fun getBundleOfParamsForFirebase(): Bundle
}
It means all generated Event classes must override both of the above-mentioned methods.
We also need a Utility(helper) class that will use Event interface classes to fire events to respective analytics SDKs.
package com.aniket.myevent
import android.util.Log
object EventUtils {
fun postEvent(event: Event) {
sendFirebaseEvent(event)
sendCustomAnalyticEvent(event)
}
private fun sendFirebaseEvent(event: Event) {
Log.i("Firebase_Event_fire", event.getBundleOfParamsForFirebase().toString())
}
private fun sendCustomAnalyticEvent(event: Event) {
Log.i("Custom_Analytics_Event_fire", event.getHashMapOfParamsForCustomAnalytics().toString())
}
}
By default IDE is not aware the generated code. So it will mark references to generated symbols unresolvable. To make an IDE to aware about the generated codes we have to add following line in app(or consumer module)/build.gradle so IDE can import correct package names.
Groovy Gradle
// app/build/gradle
buildTypes {
release {
....
sourceSets {
main {
java { srcDirs = ["src", "build/generated/ksp/release/kotlin"]}
}
}
}
debug {
....
sourceSets {
main {
java { srcDirs = ["src", "build/generated/ksp/debug/kotlin"]}
}
}
}
}
Kotlin Gradle
// app/build.gradle.kts
buildTypes {
getByName("release") {
....
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
sourceSets {
getByName("main") {
java.srcDir(File("build/generated/ksp/release/kotlin"))
}
}
}
getByName("debug") {
....
sourceSets {
getByName("main") {
java.srcDir(File("build/generated/ksp/debug/kotlin"))
}
}
}
}
Last thing do is actually trigger an Event
bookTicketButton.setOnClickListener {
EventUtils.postEvent(
TicketBookClickedParamsEvent(
TicketBookClickedParams(
eventName = "TicketBookClicked",
screenName = "MainActivity",
ticketNumber = 1223,
ticketAmount = "1220"
)
)
)
}
Let's run the app and see fired events log
Links
GitHub repo part-4 branch: https://github.com/aniketbhoite/ksp-my-event/tree/part-4
Posted on April 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.