Skip to content

Instantly share code, notes, and snippets.

@PiN73
Last active March 17, 2023 23:24
Show Gist options
  • Save PiN73/55116bb92d3f921821254fd6262b49fb to your computer and use it in GitHub Desktop.
Save PiN73/55116bb92d3f921821254fd6262b49fb to your computer and use it in GitHub Desktop.
Dart Stream making periodic requests only when has listeners
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