飞镖中的节气门功能执行

时间:2018-11-01 07:42:50

标签: dart flutter throttling rxdart

Dart中是否有办法限制这种函数的执行

Observable.throttle(myFunction,2000);

3 个答案:

答案 0 :(得分:1)

使用https://pub.dartlang.org/documentation/rxdart/latest/rx/Observable/throttle.html

因此,您在带有RxDart的Dart 2中的示例是

final subject = new ReplaySubject<int>();
myCaller(Event event) {
  subject.add(event);
}
subject
  .throttle(Duration(seconds: 2))
  .listen(myHandler);

答案 1 :(得分:1)

// you can run the code in dartpad: https://dartpad.dev/
typedef VoidCallback = dynamic Function();

class Throttler {
  Throttler({this.throttleGapInMillis});

  final int throttleGapInMillis;

  int lastActionTime;

  void run(VoidCallback action) {
    if (lastActionTime == null) {
      action();
      lastActionTime = DateTime.now().millisecondsSinceEpoch;
    } else {
      if (DateTime.now().millisecondsSinceEpoch - lastActionTime > (throttleGapInMillis ?? 500)) {
        action();
        lastActionTime = DateTime.now().millisecondsSinceEpoch;
      }
    }
  }
}

void main() {
  var throttler = Throttler();
  // var throttler = Throttler(throttleGapInMillis: 1000);
  throttler.run(() {
    print("will print");
  });
  throttler.run(() {
    print("will not print");
  });
  Future.delayed(Duration(milliseconds: 500), () {
    throttler.run(() {
      print("will print with delay");
    });
  });
}

答案 2 :(得分:0)

按照 Günter Zöchbauer 的思路,您可以使用 StreamController 将函数调用转换为 Stream。就示例而言,假设 myFunction 有一个 int 返回值和一个 int 参数。

import 'package:rxdart/rxdart.dart';

// This is just a setup for the example
Stream<int> timedMyFunction(Duration interval) {
  StreamController<int> controller;
  Timer timer;
  int counter = 0;

  void tick(_) {
    counter++;
    controller.add(myFunction(counter)); // Calling myFunction here
  }

  void startTimer() {
    timer = Timer.periodic(interval, tick);
  }

  void stopTimer() {
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
  }

  controller = StreamController<int>(
      onListen: startTimer,
      onPause: stopTimer,
      onResume: startTimer,
      onCancel: stopTimer);

  return controller.stream;
}

// Setting up a stream firing twice a second of the values of myFunction
var rapidStream = timedMyFunction(const Duration(milliseconds: 500));

// Throttling the stream to once in every two seconds
var throttledStream = rapidStream.throttleTime(Duration(seconds: 2)).listen(myHandler);