rituparna
rituparna

Reputation: 91

Wait for stream inside a Future: Flutter

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

Answers (4)

scrimau
scrimau

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

Frank van Puffelen
Frank van Puffelen

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

Peter Haddad
Peter Haddad

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

Saiful Islam Adar
Saiful Islam Adar

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

Related Questions