【问题标题】:How to convert Future<bool> into Stream<bool>如何将 Future<bool> 转换为 Stream<bool>
【发布时间】:2020-05-23 13:39:03
【问题描述】:

在我的 Flutter 应用程序中,我有一个返回 Future 的函数,但我想得到 Stream 的结果。这是函数:

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

怎么做?

【问题讨论】:

  • 你在哪里打电话isGpsOn()..?
  • 它在我的存储库层中。我想在 Bloc 模式中使用它。

标签: flutter dart


【解决方案1】:

阅读manual 并查看我的答案:

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');
});

或创建转换器:

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');
});

【讨论】:

  • "等待 Future.delayed(Duration(seconds: 5));"为什么会延迟?请解释一下。
  • @Newaj 你可以去掉它,只是为了表明它是连续的事件流。因为您正在尝试获取流,这不是一次性的。
  • @Newaj 我也添加了这个延迟以避免过于频繁地检查 gps 的状态
  • 它一直在调用该函数。但我希望它在 GPS 状态发生变化时立即调用。 StreamBuilder 之类的东西。
  • @Newaj 它基于手动调用该地理定位器服务。好的,我正在更改我的答案以更改状态。
【解决方案2】:

如果您不想更改函数的返回类型,您可以让调用者将Future&lt;T&gt; 转换为Stream&lt;T&gt;,只需在返回的asStream() 上调用Future

【讨论】:

    猜你喜欢
    • 2023-01-03
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2012-02-17
    相关资源
    最近更新 更多