Quickstart: Kotlin (Android/JVM)
Build a real-time pub/sub app in 10 minutes.
Prerequisites
- Kotlin 1.5+
- RelayX account with API key and secret
Install
Add to your build.gradle.kts:
dependencies {
implementation("com.realtime:relay:1.1.0")
}
Basic Example
import relay.Realtime
import relay.RealtimeConfig
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val config = RealtimeConfig().apply {
apiKey = "your-api-key"
secret = "your-secret"
}
val client = Realtime()
client.init(config)
await client.connect()
// Subscribe to messages
client.on("chat.room1") { msg ->
println("${msg.data["user"]}: ${msg.data["text"]}")
}
// Publish a message
client.publish("chat.room1", mapOf(
"user" to "kotlin-user",
"text" to "Hello from Kotlin!"
))
println("Message sent!")
}
Android Example
import relay.Realtime
import relay.RealtimeConfig
import kotlinx.coroutines.launch
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
class ChatViewModel : ViewModel() {
private val client = Realtime()
fun connect(context: Context) {
val config = RealtimeConfig().apply {
apiKey = "your-api-key"
secret = "your-secret"
filesDir = context.filesDir
}
client.init(config)
viewModelScope.launch {
client.connect()
client.on("chat.room1") { msg ->
// Update UI with new message
_messages.value += Message(
user = msg.data["user"] as String,
text = msg.data["text"] as String
)
}
}
}
fun sendMessage(text: String) {
viewModelScope.launch {
client.publish("chat.room1", mapOf(
"user" to "android-user",
"text" to text
))
}
}
}
Run It
- Add your API credentials
- Run the app
- Messages will appear in real-time