@textile/hub > Client > listen
Client.listen() method
listen opens a long-lived connection with a remote node, running the given callback on each new update to the given instance. The return value is a close
function, which cleanly closes the connection with the remote node.
Signature:
listen<T = any>(threadID: ThreadID, filters: Filter[], callback: (reply?: Update<T>, err?: Error) => void): grpc.Request;
Parameters
Parameter | Type | Description |
---|---|---|
threadID | ThreadID | the ID of the database |
filters | Filter[] | contains an array of Filters |
callback | (reply?: Update<T>, err?: Error) => void | The callback to call on each update to the given instance. |
Returns:
grpc.Request
Example 1
import {Client, ThreadID, Update} from '@textile/hub'
interface Astronaut {
name: string
missions: number
_id: string
}
function setupListener (client: Client, threadID: ThreadID) {
const callback = (update?: Update<Astronaut>) => {
// Not safe if more than the Astronauts collection existed in the same DB
if (!update || !update.instance) return
console.log('New update:', update.instance.name, update.instance.missions)
}
const closer = client.listen(threadID, [], callback)
return closer
}
Example 2
Listen to only CREATE events on a specific Collection.
import {Client, ThreadID, Update} from '@textile/hub'
interface Astronaut {
name: string
missions: number
_id: string
}
function setupListener (client: Client, threadID: ThreadID) {
const callback = (update?: Update<Astronaut>) => {
if (!update || !update.instance) return
console.log('New update:', update.instance.name, update.instance.missions)
}
const filters = [
{collectionName: 'Astronauts'},
{actionTypes: ['CREATE']}
]
const closer = client.listen(threadID, filters, callback)
return closer
}