Reputation: 91
I want to check if the Firebase DB is connected or not, so I have to use a Future to return a boolean
Have a check at my code..
@override
Future<bool> isAvailable() async {
bool ret = false;
await firebaseInstance.reference().child('.info/connected').onValue.listen((event) {
ret = event.snapshot.value;
});
return ret;
}
the firebaseInstace.reference is a StreamSubscription type and does not wait for the future to return me a result.
please help.
Upvotes: 1
Views: 1882
Reputation: 1385
Instead of awaiting the end of the stream subscription (it never ends), just take the first
value:
@override
Future<bool> isAvailable() => firebaseInstance.reference().child('.info/connected').onValue.first;
Upvotes: 1
Reputation: 598740
If you only need to know the current value, use once().then
instead of onValue.listen
@override
Future<bool> isAvailable() async {
var snapshot = await firebaseInstance.reference().child('.info/connected').once();
return snapshot.value;
}
Upvotes: 1
Reputation: 80914
You can do the following:
@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
returns a Stream<Event>
and then you can use await for
to iterate inside the Stream and get the data, and then it will return.
Upvotes: 0
Reputation: 221
You can put the StreamSubcription in a variable
StreamSubscription subscription = someDOMElement.onSubmit.listen((data) {
// you code here
if (someCondition == true) {
subscription.cancel();
}
});
More can be found here is there any way to cancel a dart Future?
Upvotes: 0