terminate method

Future<void> terminate()

Terminates this FirebaseFirestore instance, releasing all the resources it holds.

After this the instance cannot be used anymore: to start again, create a new instance with instanceFor. Listeners stop receiving events, and the connections and the local cache are closed.

Every operation on a terminated instance fails with a FirestoreException with the code FirestoreErrorCode.failedPrecondition, delivered through the returned future or stream. Calling terminate again does nothing.

Termination does not cancel pending writes, but a write whose future has not completed when the instance is terminated never completes (it neither succeeds nor fails). With a persistent cache the write stays in the cache and the next instance on that cache sends it; with a memory cache it is lost. Call waitForPendingWrites first when the writes matter. A transaction, an aggregation or a server read that is in flight fails.

On the Dart VM a program does not exit while an instance is alive (it holds connections and timers), so a command line program or a test terminates its instances when it is done. In a long-running app you rarely need it, except to change the settings of an instance or to call clearPersistence.

await firestore.waitForPendingWrites();
await firestore.terminate();
// FirebaseFirestore.instanceFor(app: app) now creates a new instance.

Implementation

Future<void> terminate() async {
  // The client must be initialized to ensure that all subsequent API usage
  // throws an exception.
  // Forget the instance first (as Android and JS do), so that a caller that asks for an instance while this one
  // shuts down gets a new one rather than this one.
  final List<String> keys = FirestoreMultiDbComponent.deregister(this);
  if (_clientOrNull == null && _start != null) {
    // Never used: nothing to close, and nothing is started just to be closed.
    _terminatedBeforeStart = true;
    return;
  }
  final Future<void> shutdown = client.shutdown();
  // A new instance of the same app name and database opens the cache only after this one closed it, also when it
  // is created after this instance left the registry (for example after `await app.delete()`).
  FirestoreMultiDbComponent.recordClosing(keys, shutdown);
  await shutdown;
}