如何使用异步函数异步侦听 Firestore 中的值?

mik*_*mik 0 asynchronous future dart flutter google-cloud-firestore

我在 Flutter 中有一个与 Firestore 通信的异步函数。有一个运行的服务器功能,我对任务完成的指示是我使用 StreamSubscription 监听的标志。StreamSubscription 侦听代码用 Future 异步函数包装,但我无法理解如何从 StreamSubscription 的函数处理程序返回 Future。

static Future<bool> listenToProcess(
  String doc, Function func) {

  StreamSubscription<DocumentSnapshot> stream =  Firestore.instance.collection('requests').document(doc)
      .snapshots().listen((data){
    if (data.data["done"])
      func(true);
    print ("change " + data.data["done"].toString());
  });
Run Code Online (Sandbox Code Playgroud)

}

该函数应等待流获得 done=true 未来答案。

Hug*_*sos 7

您可以Completer在这些情况下使用:

static Future<bool> listenToProcess(String doc, Function func) {
  final completer = Completer<bool>();
  final stream = Firestore.instance
      .collection('requests').document(doc).snapshots().listen((data) {
        ...
        completer.complete(data.data["done"]);
      });

  return completer.future;
}

Run Code Online (Sandbox Code Playgroud)

但是,我看到您可能在这里混淆了一些概念。

  1. 您的函数名称表明它正在处理 a Stream,但是您返回的是 a Future。您不应在同一函数中同时使用StreamFuture概念。这有点令人困惑。

  2. 您正在传递 callback func,但是当您已经返回 a 时不打算使用它们Future,因为您可以funcFuture解析时调用。

我会像这样重写这个函数:

static Future<bool> checkIfRequestIsDone(String doc) async {
  // Retrieve only the first snapshot. There's no need to listen to it.
  DocumentSnapshot snapshot = await Firestore.instance
      .collection('requests').document(doc).snapshots().first;

  return snapshot["done"];
}
Run Code Online (Sandbox Code Playgroud)

和来电者:

bool isRequestDone = await checkIfRequestIsDone(doc);

// Call the server-function as soon as you know if the request is done.
// No need for callback.
serverFunction(isRequestDone); 
Run Code Online (Sandbox Code Playgroud)