Line data Source code
1 : import 'dart:async'; 2 : 3 : /// Takes a [task] and makes sure that [trigger] does execute the task only 4 : /// one time in a run loop cycle. 5 : class GgOncePerCycle { 6 : /// The [task] to be triggered only one time in a run loop cycle. 7 : /// 8 : /// If [isTest] is true, task will not be executed automatically. 9 : /// In that case call [executeNow()]. 10 : /// 11 : /// If [scheduleTask] callback is set, tasks will be scheduled using this 12 : /// function. Otherwise dart's [scheduleMicrotask] will be used. 13 1 : GgOncePerCycle({ 14 : required this.task, 15 : this.isTest = false, 16 : this.scheduleTask = scheduleMicrotask, 17 : }); 18 : 19 : /// Call this method if triggered tasks shoult not be triggered anymore 20 1 : void dispose() { 21 1 : _isDisposed = true; 22 : } 23 : 24 : /// The task to be triggered 25 : void Function() task; 26 : 27 : /// This method triggers the task, but only if it has not already been 28 : /// executed during this run loop cycle. 29 : /// 30 : /// [If scheduleTask is set, this method will used to trigger the task] 31 1 : void trigger({ 32 : void Function(void Function() task)? scheduleTask, 33 : }) { 34 1 : if (_isTriggered) { 35 : return; 36 : } 37 : 38 1 : _isTriggered = true; 39 : 40 1 : if (isTest) { 41 : return; 42 : } 43 : 44 3 : (scheduleTask ?? this.scheduleTask).call(_scheduledTask); 45 : } 46 : 47 : /// The task will only be triggered once in a cycle. 48 : /// Use `[isTest] = false` and `executeNow()` to control the execution. 49 2 : void executeNow() => _scheduledTask(); 50 : 51 : bool _isTriggered = false; 52 : bool _isDisposed = false; 53 : 54 : /// Returns true if this is run in a test environmen 55 : final bool isTest; 56 : 57 1 : void _scheduledTask() { 58 1 : _isTriggered = false; 59 1 : if (!_isDisposed) { 60 2 : task(); 61 : } 62 : } 63 : 64 : /// Use this method to schedule a task 65 : late void Function(void Function() task) scheduleTask; 66 : }