如何使用异步函数异步监听FiRestore中的值? [英] How do I asynchronously listen to a value in Firestore using an async function?

查看:21
本文介绍了如何使用异步函数异步监听FiRestore中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ffltter中有一个与FiRestore通信的异步函数。 有一个运行的服务器函数,我对任务完成的指示是我使用StreamSubcription监听的标志。 StreamSubcription侦听代码用Future Async函数包装,但我无法理解如何从StreamSubcription的函数处理程序返回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());
  });

}

该函数应等待流获得Done=True将来的答案。

推荐答案

您可以在以下情况下使用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;
}

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

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

  2. 您正在传递回调func,但这些回调不应该在您已经返回Future时使用,因为您可以在Future解析时调用func

我将重写此函数,如下所示:

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"];
}

和呼叫者:

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); 

这篇关于如何使用异步函数异步监听FiRestore中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆