forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream-timeout-between-events-in-flutter.dart
115 lines (97 loc) · 2.58 KB
/
stream-timeout-between-events-in-flutter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// 🐦 Twitter https://twitter.com/vandadnp
// 🔵 LinkedIn https://linkedin.com/in/vandadnp
// 🎥 YouTube https://youtube.com/c/vandadnp
// 🤝 Want to support my work? https://youtube.com/c/vandadnp/join/
// import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:developer' as devtools show log;
void main() {
runApp(
const App(),
);
}
extension Log on Object {
void log() => devtools.log(toString());
}
class TimeoutBetweenEvents<E> extends StreamTransformerBase<E, E> {
final Duration duration;
const TimeoutBetweenEvents({required this.duration});
@override
Stream<E> bind(Stream<E> stream) {
StreamController<E>? controller;
StreamSubscription? subscription;
Timer? timer;
controller = StreamController(
onListen: () {
subscription = stream.listen(
(data) {
timer?.cancel();
timer = Timer.periodic(duration, (_) {
controller?.addError(
TimeoutBetweenEventsException('Timeout'),
);
});
controller?.add(data);
},
onError: controller?.addError,
onDone: controller?.close,
);
},
onCancel: () {
subscription?.cancel();
timer?.cancel();
},
);
return controller.stream;
}
}
class TimeoutBetweenEventsException implements Exception {
final String message;
TimeoutBetweenEventsException(this.message);
}
extension WithTimeoutBetweenEvents<T> on Stream<T> {
Stream<T> withTimeoutBetweenEvents(Duration duration) =>
transform(TimeoutBetweenEvents(duration: duration));
}
Stream<String> getNames() async* {
yield 'John';
await Future.delayed(const Duration(seconds: 1));
yield 'Jane';
await Future.delayed(const Duration(seconds: 10));
yield 'Doe';
}
Future<void> testIt() async {
await for (final name in getNames().withTimeoutBetweenEvents(
const Duration(
seconds: 3,
),
)) {
name.log();
}
}
class App extends StatelessWidget {
const App({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
testIt();
return Scaffold(
appBar: AppBar(
title: const Text('Home Page'),
),
);
}
}