How to convert Future<bool> into Stream<bool>

Viewed 2103

In my Flutter app, I have a function returning Future, but I wanna get result as Stream. Here is the function :

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

How to do that?

2 Answers

Read the manual and check my answer:

Stream<bool> gpsStatusStream() async* {
  bool enabled;
  while (true) {
    try {
      bool isEnabled = await Geolocator().isLocationServiceEnabled();
      if (enabled != isEnabled) {
        enabled = isEnabled;
        yield enabled;
      }
    }
    catch (error) {}
    await Future.delayed(Duration(seconds: 5));
  }
}
gpsStatusStream().listen((enabled) {
  print(enabled ? 'enabled' : 'disabled');
});

or create convertor:

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);
  }
}
Future<bool> isGpsOn() async {
  return await Geolocator().isLocationServiceEnabled();
}
final gpsStatusStream = futureToStream(isGpsOn, false, Duration(seconds: 5));
gpsStatusStream.listen((enabled) {
  print(enabled ? 'enabled' : 'disabled');
});

If you don't want to change the return type of your function, you could make callers convert the Future<T> to a Stream<T> by simply calling asStream() on the returned Future.

Related