dehaze

Sample use cases

The following are a few use cases for using subscription:

Realtime chat app

If you want to build a realtime chat app, then you can use Space Cloud for various realtime features in your app like:

  • Realtime stream of chat messages
  • Online / offline status of a user
  • Is typing indicator for a user

Example: Subscribe to chat messages:

subscription {
  messages @mongo (
    where: {to: {_eq: "user1"}}
  ){
    type
    payload {
      _id
      from
      to
      text 
      timestamp
    }
    docId
  }
}
const whereClause = cond("to", "==", "user1")

// Callback for data changes:
const onSnapshot  = (messages, type, 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 @mongo (
    where: {_id: {_eq: "user2"}}
  ){
    type
    payload {
      _id
      status
      is_typing
    }
    docId
  }
}
const whereClause = cond("_id", "==", "user2")

// Callback for data changes:
const onSnapshot  = (_, type, 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()
}

Live score updates

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 @mongo (
    where: {_id: {_eq: "1"}}
  ){
    type
    payload {
      score
    }
  }
}
const whereClause = cond("_id", "==", "1")

// Callback for data changes:
const onSnapshot  = (_, type, 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()
}

Have a technical question?

Improve the docs!