1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
rituparna
  • 91
  • 1
  • 12

4 Answers4

2

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;
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

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;
scrimau
  • 1,325
  • 1
  • 14
  • 27
0

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?

0

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.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134