Flutter中stream学习

概述

Stream 主要应用于 Flutter 的异步操作,在其他编程语言中也存在;Stream 提供了一种接受事件队列的方法,可通过 listen 进行数据监听,通过 error 接收失败状态,通过 done 来接收结束状态;

Stream的基础概念

  • Stream:表示一个可以接收异步事件的数据源。可以生成一个或多个值。
  • StreamController:控制Stream,可以向其添加事件、错误以及关闭它。
  • StreamSubscription:表示对Stream的监听,可以用来取消订阅。
  • Sink:用来向Stream添加数据、错误、以及关闭。

stream的常用方法

Stream.fromFuture(Future future)

Stream通过Future对象创建新的单订阅流, 当Future对象完成时会触发 data / error, 然后已done事件结束

Future<String> getDate() async {
   
   
    await Future.delayed(const Duration(seconds: 3));

    return "当前时间为${DateTime.now()}";
  }

  void testStreamFromFuture() {
   
   
    Stream.fromFuture(getDate()).listen((event) {
   
   
      print("testStreamFromFuture============$event");
    }).onDone(() {
   
   
      print("testStreamFromFuture==========done 结束");
    });
  }

输出结果:
在这里插入图片描述

Stream.fromFutures(Iterable<Future> futures)

Stream 通过一系列的 Future 创建新的单订阅流,每个 Future 都会有自身的 data / error 事件, 当这一系列的 Future 均完成时,Stream 以 done 事件结束;若 Futures 为空,则 Stream 会立刻关闭;其分析源码,很直接的看到是将每一个 Future 事件监听完之后才会执行的微事件结束;

源码代码:

factory Stream.fromFutures(Iterable<Future<T>> futures) {
   
   
    _StreamController<T> controller =
        new _SyncStreamController<T>(null, null, null, null);
    int count = 0;
    // Declare these as variables holding closures instead of as
    // function declarations.
    // This avoids creating a new closure from the functions for each future.
    void onValue(T value) {
   
   
      if (!controller.isClosed) {
   
   
        controller._add(value);
        if (--count == 0) controller._closeUnchecked();
      }
    }

    void onError(Object error, StackTrace stack) {
   
   
      if (!controller.isClosed) {
   
   
        controller._addError(error, stack);
        if (--count == 0) controller._closeUnchecked();
      }
    }

    // The futures are already running, so start listening to them immediately
    // (instead of waiting for the stream to be listened on).
    // If we wait, we might not catch errors in the futures in time.
    for (var future in futures) {
   
   
      count++;
      future.then(onValue, onError: onError);
    }
    // Use schedule microtask since controller is sync.
    if (count == 0) scheduleMicrotask(controller.close);
    return controller.stream;
  }

示例代码:

var datas = [getDate(), getDate(), getDate()];
    Stream.fromFutures(datas).listen((event) {
   
   
      print("testStreamFromFutures============$event");
    }).onDone(() {
   
   
      print("testStreamFromFutures==========done 结束");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值