Last active
March 17, 2023 23:24
-
-
Save PiN73/55116bb92d3f921821254fd6262b49fb to your computer and use it in GitHub Desktop.
Dart Stream making periodic requests only when has listeners
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
import 'dart:async'; | |
class MyStream { | |
late final _controller = StreamController<String>.broadcast( | |
onListen: _startTimer, | |
onCancel: _stopTimer, | |
); | |
Timer? _timer; | |
Stream<String> get stream => _controller.stream; | |
void _startTimer() { | |
_timer ??= Timer.periodic(Duration(seconds: 1), _makeRequest); | |
} | |
void _stopTimer() { | |
if (!_controller.hasListener) { | |
_timer?.cancel(); | |
_timer = null; | |
} | |
} | |
void _makeRequest(Timer timer) { | |
String result = "${DateTime.now().second}"; | |
print('requested $result'); | |
_controller.add(result); | |
} | |
void dispose() { | |
_controller.close(); | |
} | |
} | |
void main() async { | |
final myStream = MyStream(); | |
final subscriptionA = myStream.stream.listen((result) { | |
print('A $result'); | |
}); | |
await Future.delayed(Duration(seconds: 3)); | |
final subscriptionB = myStream.stream.listen((result) { | |
print('B $result'); | |
}); | |
await Future.delayed(Duration(seconds: 3)); | |
subscriptionA.cancel(); | |
await Future.delayed(Duration(seconds: 3)); | |
subscriptionB.cancel(); | |
await Future.delayed(Duration(seconds: 3)); | |
final subscriptionC = myStream.stream.listen((result) { | |
print('C $result'); | |
}); | |
await Future.delayed(Duration(seconds: 3)); | |
subscriptionC.cancel(); | |
await Future.delayed(Duration(seconds: 3)); | |
myStream.dispose(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment