Throttle function execution in dart

Viewed 5089

Is there a way in Dart to throttle function execution like this

Observable.throttle(myFunction,2000);

4 Answers
// 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");
    });
  });
}

Along the lines of Günter Zöchbauer you can use a StreamController to transform the function calls to a Stream. For the sake of the example let's say that myFunction has an int return value and an int parameter.

import 'package:rxdart/rxdart.dart';

// This is just a setup for the example
Stream<int> timedMyFunction(Duration interval) {
  late 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);
import 'package:flutter/foundation.dart';
import 'dart:async';

// A simple class for throttling functions execution
class Throttler {
  @visibleForTesting
  final int milliseconds;

  @visibleForTesting
  Timer? timer;

  @visibleForTesting
  static const kDefaultDelay = 2000;

  Throttler({this.milliseconds = kDefaultDelay});

  void run(VoidCallback action) {
    if (timer?.isActive ?? false) return;

    timer?.cancel();
    action();
    timer = Timer(Duration(milliseconds: milliseconds), () {});
  }

  void dispose() {
    timer?.cancel();
  }
}

// How to use
void main() {
  var throttler = Throttler();

  throttler.run(() {
    print("will print");
  });
  throttler.run(() {
    print("will not print");
  });
  Future.delayed(const Duration(milliseconds: 2000), () {
    throttler.run(() {
      print("will print with delay");
    });
  });

  throttler.dispose();
}
Related