我想检查Firebase DB是否连接,所以我必须使用Future来返回一个boolean值。
检查一下我的代码...
@override
Future<bool> isAvailable() async {
bool ret = false;
await firebaseInstance.reference().child('.info/connected').onValue.listen((event) {
ret = event.snapshot.value;
});
return ret;
}
firebaseInstace.reference是一个StreamSubscription类型,并没有等待未来返回结果。
请帮助我。
如果你只需要知道当前值,使用 once().then
而不是 onValue.listen
@override
Future<bool> isAvailable() async {
var snapshot = await firebaseInstance.reference().child('.info/connected').once();
return snapshot.value;
}
你可以把StreamSubcription放在一个变量中
StreamSubscription subscription = someDOMElement.onSubmit.listen((data) {
// you code here
if (someCondition == true) {
subscription.cancel();
}
});
更多信息可以在这里找到 有什么方法可以取消未来的飞镖?
你可以做以下操作。
@override
Future<bool> isAvailable() async {
bool ret = false;
Stream<Event> events =
FirebaseDatabase.instance.reference().child('.info/connected').onValue;
await for (var value in events) {
ret = value.snapshot.value;
}
return ret;
}
onValue
返回一个 Stream<Event>
然后你可以使用 await for
来在Stream内部迭代并获取数据,然后它将返回。
而不是等待流订阅的结束(它永远不会结束),只需将它的 first
价值。
@override
Future<bool> isAvailable() => firebaseInstance.reference().child('.info/connected').onValue.first;