Is there any method like onDisconnect() in firestore like there is in realtime database?

According to this onDisconnect:

The onDisconnect class is most commonly used to manage presence in applications where it is useful to detect how many clients are connected and when other clients disconnect.

To be able to use presence in firestore, you need to connect firestore with realtime firebase(no other way).

Please check this for more info:

https://firebase.google.com/docs/firestore/solutions/presence


NOTE: This solution is not especially efficient

Off the top of my head (read: I haven't thought through the caveats), you could do something like this:

const fiveMinutes = 300000 // five minutes, or whatever makes sense for your app

// "maintain connection"
setInterval(() => {
  userPresenceDoc.set({ online: new Date().getTime() })
}, fiveMinutes)

then, on each client...

userPresenceDoc.onSnapshot(doc => {
  const fiveMinutesAgo = new Date().getTime() - fiveMinutes
  const isOnline = doc.data().online > fiveMinutesAgo
  setUserPresence(isOnline)
})

You'd probably want the code checking for presence to use an interval a little more than the interval used by the code maintaining the connection to account for network lag, etc.

A NOTE ABOUT COST

So, obviously, there could be significant lag between when someone disconnects and when that disconnection is recognized by other clients. You can decrease that lag time by increasing the frequency of writes to Firestore, and thus increasing your costs. Running the numbers, I came out with the following costs for different intervals, assuming a single client connection running continuously for a month:

Interval     Cost/User/Month
----------------------------
10m          $0.007776
 5m          $0.015552
 1m          $0.07776
10s          $0.46656
 5s          $0.93312
 1s          $4.6656

Going with an interval of one second is pretty pricy, at $46,656 a month for a system with 10,000 users who leave the app open all month long. An interval of 10 minutes with the same number of users would only cost $77.76 a month. A more reasonable interval of one minute, 10,000 users, and only four hours of app usage per day per user, rings in at $129.60 / month.


There is no equivalent. The Firestore SDK currently doesn't have presence management like the Realtime Database SDK.

Instead, you might want to use the Realtime Database onDisconnect() in conjunction with Cloud Functions to kick off some work when the client disconnects from RTDB. You would be assuming that that your app probably also lost its connection to Firestore at the same time.