我在 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());
});
该函数应等待流获得 done=true future 答案。
最佳答案
您可以使用 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;
}
但是,我发现您可能在这里混淆了一些概念。
您的函数名称表明它正在处理一个
Stream
,但是您返回的是一个Future
。您不应在同一函数中同时使用Stream
和Future
概念。这有点令人困惑。您正在传递回调函数
func
,但是当您已经返回一个Future
时不打算使用它们,因为您可以调用func
当Future
解析时。
我会像这样重写这个函数:
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);
关于asynchronous - 如何使用异步函数异步监听 Firestore 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57450131/