Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streams equivalent to Observable.Throttle?

Is there a Streams equivalent to Observable.Throttle? If not -- is there any reasonably elegant way to achieve a similar effect?

like image 776
w.brian Avatar asked Feb 25 '13 16:02

w.brian


1 Answers

There's no such method on streams for now. A enhancement request has been filed, you can star issue 8492.

However, you can do that with the where method. In the following exemple, I have defined a ThrottleFilter class to ignore events during a given duration :

import 'dart:async';

class ThrottleFilter<T> {
  DateTime lastEventDateTime = null;
  final Duration duration;

  ThrottleFilter(this.duration);

  bool call(T e) {
    final now = new DateTime.now();
    if (lastEventDateTime == null ||
        now.difference(lastEventDateTime) > duration) {
      lastEventDateTime = now;
      return true;
    }
    return false;
  }
}

main() {
  final sc = new StreamController<int>();
  final stream = sc.stream;

  // filter stream with ThrottleFilter
  stream.where(new ThrottleFilter<int>(const Duration(seconds: 10)).call)
    .listen(print);

  // send ints to stream every second, but ThrottleFilter will give only one int
  // every 10 sec.
  int i = 0;
  new Timer.repeating(const Duration(seconds:1), (t) { sc.add(i++); });
}
like image 200
Alexandre Ardhuin Avatar answered Sep 21 '22 19:09

Alexandre Ardhuin