Created
August 8, 2024 13:06
-
-
Save Pamblam/f7d5ed5ea76a4ef6bc86a16ff1666828 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An example of a singleton that does some polling for an event | |
* and calls a callback when the event is fired. | |
*/ | |
import 'dart:async'; | |
void main() { | |
print("Running.."); | |
EventListener listener = EventListener()..addCallback(EventHandler( | |
event: 3, | |
callback: ()=>print('3 did up in this bitch') | |
)); | |
EventListener listener2 = EventListener()..addCallback(EventHandler( | |
event: 5, | |
callback: ()=>print('5 did up in this bitch') | |
)); | |
} | |
class EventHandler{ | |
int event; | |
Function callback; | |
EventHandler({ | |
required this.event, | |
required this.callback | |
}); | |
} | |
class EventListener{ | |
static final EventListener _instance = EventListener._internal(); | |
static int _counter = 0; | |
static List<EventHandler> _handlers = []; | |
static Timer? _timer; | |
EventListener._internal(); | |
factory EventListener(){ | |
return _instance; | |
} | |
void addCallback(EventHandler listener){ | |
_handlers.add(listener); | |
if(_timer == null) _pollTheThing(); | |
} | |
void cancelPolling(){ | |
if(null != _timer){ | |
_timer?.cancel(); | |
_timer = null; | |
} | |
} | |
void _pollTheThing(){ | |
_timer = Timer.periodic(Duration(seconds: 5), (timer) async { | |
List<int> indexesToRemove = []; | |
for(int i=0; i<_handlers.length; i++){ | |
if(_handlers[i].event == _counter){ | |
indexesToRemove.add(i); | |
_handlers[i].callback(); | |
} | |
} | |
for(int i=0; i<indexesToRemove.length; i++){ | |
_handlers.removeAt(indexesToRemove[i]); | |
} | |
if(_handlers.isEmpty){ | |
cancelPolling(); | |
} | |
print('Counter: $_counter'); | |
_counter++; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment