The following are a few use cases for using subscription:
If you want to build a realtime chat app, then you can use Space Cloud for various realtime features in your app like:
Example: Subscribe to chat messages:
subscription {
messages (
where: {to: {_eq: "user1"}}
) @mongo {
type
payload {
_id
from
to
text
timestamp
}
docId
}
}
const whereClause = cond("to", "==", "user1")
// Callback for data changes:
const onSnapshot = (messages, type, find, message) => {
}
// Callback for error while subscribing
const onError = (err) => {
console.log('Live query error', err)
}
let subscription = db.liveQuery("messages")
.where(whereClause)
.subscribe(onSnapshot, onError)
// Unsubscribe to changes
if (on some logic) {
subscription.unsubscribe()
}
Example: Subscribe to is_typing indicator and status of a user:
subscription {
users (
where: {_id: {_eq: "user2"}}
) @mongo {
type
payload {
_id
status
is_typing
}
docId
}
}
const whereClause = cond("_id", "==", "user2")
// Callback for data changes:
const onSnapshot = (_, type, find, user) => {
}
// Callback for error while subscribing
const onError = (err) => {
console.log('Live query error', err)
}
let subscription = db.liveQuery("users")
.where(whereClause)
.subscribe(onSnapshot, onError)
// Unsubscribe to changes
if (on some logic) {
subscription.unsubscribe()
}
Let’s say you want to display the score of a particular game in realtime without polling the database again and again. In this case, you can subscribe to the game score and get notified whenever it’s updated.
subscription {
games (
where: {_id: {_eq: "1"}}
) @mongo {
type
payload {
score
}
}
}
const whereClause = cond("_id", "==", "1")
// Callback for data changes:
const onSnapshot = (_, type, find, game) => {
}
// Callback for error while subscribing
const onError = (err) => {
console.log('Live query error', err)
}
let subscription = db.liveQuery("games")
.where(whereClause)
.subscribe(onSnapshot, onError)
// Unsubscribe to changes
if (on some logic) {
subscription.unsubscribe()
}