如何在每一秒钟返回布尔的颤音中创建流

发布于 2025-02-13 17:14:06 字数 70 浏览 1 评论 0原文

我正在制作一个应用程序。我想检查我的服务器状态,并提供用户信息 关于服务器。我该怎么做。流对此有好处。有些人可以为我提供代码。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尬尬 2025-02-20 17:14:06

使用AsyncMap

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

Use asyncMap

Stream<String> checkConnectionStream() async* {
  yield* Stream.periodic(Duration(seconds: 1), (_) {
    return //your function
  }).asyncMap((event) async => await event);
}
少跟Wǒ拽 2025-02-20 17:14:06

只需遵循本指南
假设您的bool返回值函数是

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

,这是从bool值创建流

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

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');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文