Home > Net >  how to create a stream in flutter that return a bool in every second
how to create a stream in flutter that return a bool in every second

Time:07-07

i am making a app. And i want to check my server state every minite and give user information about the server. How do i do it. is stream good for it. Can some provide me a code for that.

CodePudding user response:

just follow this guide suppose your bool return value function is

Future<bool> isGpsOn() async {
  return await Geolocator().isLocationServiceEnabled();
}

and this is create stream from bool value

Stream futureToStream(fn, defaultValue, Duration duration) async* {
  var result;
  while (true) {
    try {
      result = await fn();
    }
    catch (error) {
      result = defaultValue;
    }
    finally {
      yield result;
    }
    await Future.delayed(duration);
  }
}
final gpsStatusStream = futureToStream(isGpsOn, false, Duration(seconds: 5));
gpsStatusStream.listen((enabled) {
  print(enabled ? 'enabled' : 'disabled');
});

CodePudding user response:

Use asyncMap

Stream<String> checkConnectionStream() async* {
  yield* Stream.periodic(Duration(seconds: 1), (_) {
    return //your function
  }).asyncMap((event) async => await event);
}
  • Related