CollectionReferenceFake.stateful constructor

CollectionReferenceFake.stateful(
  1. String path, {
  2. Where? where,
  3. void onChanged(
    1. Map<String, DocumentReferenceFake> documents
    )?,
  4. Duration latency = const Duration(milliseconds: 100),
})

Implementation

factory CollectionReferenceFake.stateful(
  String path, {
  Where where,
  void Function(Map<String, DocumentReferenceFake> documents)? onChanged,
  Duration latency = const Duration(milliseconds: 100),
}) {
  final documents = <String, DocumentReferenceFake>{};

  //Fires the first onChanged on the collection so we can get first on the
  //stream
  Future<void>.delayed(
    latency,
    () => onChanged?.call(documents),
  );

  return CollectionReferenceFake(
    path,
    //documents,
    add: (data) async => Future<DocumentReferenceFake>.delayed(
      latency,
      () {
        final documentId = const Uuid().v4();
        final documentReference = DocumentReferenceFake.stateful(
          documentId,
          data,
          () => onChanged?.call(documents),
        );

        documents[documentId] = documentReference;
        onChanged?.call(documents);
        return documentReference;
      },
    ),
    //TODO: Call onChanged when a set or update comes from the
    //DocumentReferenceFake
    doc: (id) {
      if (!documents.containsKey(id)) {
        documents.addAll(<String, DocumentReferenceFake>{
          id!: DocumentReferenceFake.stateful(
            id,
            {},
            () => onChanged?.call(documents),
          )
        });
        onChanged?.call(documents);
      }
      return documents[id]!;
    },
    where: where,
  );
}