Best practices for cleanly closing a Database?

If you look at com.couchbase.lite.AbstractDatabase’s close method, it will throw an exception if you have any active Replicator or LiveQuery associated with the database.

    if (activeReplications.size() > 0) {
        throw new CouchbaseLiteException(
                "Cannot close the database.  Please stop all of the replicators before closing the database.",
                CBLError.Domain.CBLErrorDomain, CBLError.Code.CBLErrorBusy);
    }
    if (activeLiveQueries.size() > 0) {
        throw new CouchbaseLiteException(
                "Cannot close the database.  Please remove all of the query listeners before closing the database.",
                CBLError.Domain.CBLErrorDomain, CBLError.Code.CBLErrorBusy);
    }

The user jean-maxime wrote about tracking active replicators in client code (Replicator with couchbase lite android 2.0) and from the responses given, it sounds like this is something the clients have to do.

It seems overly complicated and redundant to track Replicator and Query instances in client code instead of directly using something like activeReplications and activeLiveQueries as in the snippet above. Is there a way to avoid writing my own (thread-safe!) data structures for this? What’s the best practice to ensure that a database is the correct state to be closed?

Edit: using Android and Couchbase Lite 2.0.0

CBL 1.x used to shut down replications and queries when closing a database, but this turned out to be problematic, since replicators could take a while to stop if there were network connectivity problems, and this would cause Database.close to block for a long time.

Yes, you do need to keep track of your replications and live queries. Generally an app doesn’t have many of these; usually just one replicator for example. So it shouldn’t be too hard to keep track of them. Otherwise yes, you can just make a global collection object and add them to it.