Skip to content
BunBase BunBase BunBase Docs Alpha v0.1.0

Realtime

let posts = client.collection("posts", type: Post.self)
let sub = client.realtime.subscribe(channel: posts.channel, type: Post.self) { event in
switch event.event {
case .create: print("New: \(event.record.title)")
case .update: print("Updated: \(event.record.title)")
case .delete: print("Deleted")
}
}
// Unsubscribe when done
sub.cancel()

Subscription cancels automatically when it is deallocated (deinit). Store it as a property to keep it alive.

let sub = client.realtime.subscribe(
channel: posts.recordChannel(id: "post_id"),
type: Post.self
) { event in
print("Record changed: \(event.record)")
}
let sub = client.realtime.subscribe(
channel: posts.channel,
type: Post.self,
options: SubscribeOptions(events: [.create])
) { event in
print("New post: \(event.record.title)")
}
let sub = client.realtime.subscribe(
channel: posts.channel,
type: Post.self,
options: SubscribeOptions(filter: ["status": "published"])
) { event in
// Only events where post.status == "published"
}
let sub = client.realtime.subscribe(channel: posts.mineChannel, type: Post.self) { event in
// Only records owned by the authenticated user
}
let sub = client.realtime.subscribe(
channel: posts.recordsChannel,
type: Post.self,
options: SubscribeOptions(ids: ["id_1", "id_2", "id_3"])
) { event in
// Events for any of the listed IDs
}
try await client.realtime.ping()
let userIds = try await client.realtime.presence(channel: "collection:chat")
print("Online: \(userIds)")
let channels = try await client.realtime.getSubscriptions()
print(channels)
class ChatViewModel: ObservableObject {
private var sub: Subscription?
func startListening() {
sub = client.realtime.subscribe(channel: "collection:messages", type: Message.self) { event in
DispatchQueue.main.async { self.handle(event) }
}
}
// sub is cancelled when the ViewModel is deallocated
}
// 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 clears tokens and fires onAuthRevoked. This is wired up in BunBaseClient — no extra setup needed.

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