如何使用异步函数异步侦听 Firestore 中的值?
How do I asynchronously listen to a value in Firestore using an async function?
我在 Flutter 中有一个与 Firestore 通信的异步函数。
有一个运行的服务器功能,我的任务完成指示是我使用 StreamSubscription 收听的标志。
StreamSubscription 侦听代码包含一个 Future 异步函数,但我无法理解如何从 StreamSubscription 的函数处理程序中 return 一个 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;
}
但是,我发现您可能在这里混淆了一些概念。
您的函数名称表明它正在处理 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);
我在 Flutter 中有一个与 Firestore 通信的异步函数。 有一个运行的服务器功能,我的任务完成指示是我使用 StreamSubscription 收听的标志。 StreamSubscription 侦听代码包含一个 Future 异步函数,但我无法理解如何从 StreamSubscription 的函数处理程序中 return 一个 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;
}
但是,我发现您可能在这里混淆了一些概念。
您的函数名称表明它正在处理
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);