Skip to content
BunBase BunBase BunBase Docs Alpha v0.1.0

Realtime

import com.bunbase.sdk.SubscribeOptions
data class Post(val title: String, val body: String)
val posts = client.collection("posts", Post::class.java)
val sub = client.realtime.subscribe<Post>(posts.channel) { event ->
when (event.event) {
RealtimeEventType.create -> println("New: ${event.record.title}")
RealtimeEventType.update -> println("Updated: ${event.record.title}")
RealtimeEventType.delete -> println("Deleted")
}
}
// Unsubscribe when done (e.g., in onCleared)
sub.cancel()

Subscription is automatically cancelled when garbage-collected, but always call cancel() explicitly in lifecycle methods.

val sub = client.realtime.subscribe<Post>(posts.recordChannel("post_id")) { event ->
println("Record changed: ${event.record}")
}
val sub = client.realtime.subscribe<Post>(
channel = posts.channel,
options = SubscribeOptions(events = listOf(RealtimeEventType.create)),
) { event ->
println("New post: ${event.record.title}")
}
val sub = client.realtime.subscribe<Post>(
channel = posts.channel,
options = SubscribeOptions(filter = mapOf("status" to "published")),
) { event ->
// Only events where post.status == "published"
}
val sub = client.realtime.subscribe<Post>(posts.mineChannel) { event ->
// Only records owned by the authenticated user
}
val sub = client.realtime.subscribe<Post>(
channel = posts.recordsChannel,
options = SubscribeOptions(ids = listOf("id_1", "id_2", "id_3")),
) { event ->
// events for any of the listed IDs
}
lifecycleScope.launch {
try {
client.realtime.ping()
println("Connected")
} catch (e: BunBaseError.Timeout) {
println("No response")
}
}
val userIds = client.realtime.presence("collection:chat")
println("Online: $userIds")
val channels = client.realtime.getSubscriptions()
println(channels)
class ChatViewModel : ViewModel() {
private var sub: Subscription? = null
fun startListening() {
sub = client.realtime.subscribe<Message>(channel) { event ->
// Handle message
}
}
override fun onCleared() {
sub?.cancel()
}
}
// Eagerly open the connection (auth events delivered immediately)
client.realtime.connect()
// Close and stop reconnecting
client.realtime.disconnect()

When the server pushes a session_revoked or account_deleted event, the SDK automatically:

  1. Clears tokens from memory and EncryptedSharedPreferences.
  2. Emits null on auth.currentUser.
  3. Closes the WebSocket.

No extra setup required.

The SDK reconnects automatically on unexpected close with exponential backoff: 500 ms, 1 s, 2 s, … up to 30 s.