I want to use Kotlin Flow to "wait" for a document while replication, is this the best way?

fun getDocumentFlow(id: String): Flow<Document> = callbackFlow {
    val document = database.getDocument(id)
    if (document == null) {
        val token = database.addDocumentChangeListener(id) { change ->
            val doc = database.getDocument(change.id)
            if (doc != null) offer(doc)
        }
        awaitClose { database.removeDocumentChangeListener(token) }
    } else {
        offer(document)
    }
}

This way will work, though it might be slightly better to use the document change listener on the replicator instead of the database, so that you don’t get noise from local changes made to the database.