Spec-Zone.ru › Dart 1

dart:async

Конструктор фабрики Stream.periodic

Stream.periodic(Duration period, [ T computation(int computationCount) ])

Создаёт поток, который многократно излучает события через интервалы period.

Значения событий вычисляются путём вызова computation. Аргументом этого обратного вызова является целое число, которое начинается с 0 и увеличивается на единицу для каждого события.

Если computation опущено, значения событий будут все null.

Исходный код

factory Stream.periodic(Duration period,
    [T computation(int computationCount)]) {
  Timer timer;
  int computationCount = 0;
  StreamController<T> controller;
  // Counts the time that the Stream was running (and not paused).
  Stopwatch watch = new Stopwatch();

  void sendEvent() {
    watch.reset();
    T data;
    if (computation != null) {
      try {
        data = computation(computationCount++);
      } catch (e, s) {
        controller.addError(e, s);
        return;
      }
    }
    controller.add(data);
  }

  void startPeriodicTimer() {
    assert(timer == null);
    timer = new Timer.periodic(period, (Timer timer) {
      sendEvent();
    });
  }

  controller = new StreamController<T>(
      sync: true,
      onListen: () {
        watch.start();
        startPeriodicTimer();
      },
      onPause: () {
        timer.cancel();
        timer = null;
        watch.stop();
      },
      onResume: () {
        assert(timer == null);
        Duration elapsed = watch.elapsed;
        watch.start();
        timer = new Timer(period - elapsed, () {
          timer = null;
          startPeriodicTimer();
          sendEvent();
        });
      },
      onCancel: () {
        if (timer != null) timer.cancel();
        timer = null;
        return Future._nullFuture;
      });
  return controller.stream;
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/1.24.3/dart-async/Stream/Stream.periodic.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API