|
| 1 | +// 🐦 Twitter https://twitter.com/vandadnp |
| 2 | +// 🔵 LinkedIn https://linkedin.com/in/vandadnp |
| 3 | +// 🎥 YouTube https://youtube.com/c/vandadnp |
| 4 | +// 💙 Free Flutter Course https://linktr.ee/vandadnp |
| 5 | +// 📦 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY |
| 6 | +// 🔶 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI |
| 7 | +// 🦄 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro |
| 8 | +// 🤝 Want to support my work? https://buymeacoffee.com/vandad |
| 9 | + |
| 10 | +import 'dart:async'; |
| 11 | +import 'dart:developer' as devtools show log; |
| 12 | + |
| 13 | +extension Log<T> on T? { |
| 14 | + void log() => devtools.log(this == null ? 'null' : toString()); |
| 15 | +} |
| 16 | + |
| 17 | +class ErrorAbsorberTransformer<T> extends StreamTransformerBase<T, T> { |
| 18 | + final _controller = StreamController<T>.broadcast(); |
| 19 | + ErrorAbsorberTransformer(); |
| 20 | + |
| 21 | + @override |
| 22 | + Stream<T> bind(Stream<T> stream) { |
| 23 | + final sub = stream |
| 24 | + .handleError( |
| 25 | + (_) => _controller.close(), |
| 26 | + ) |
| 27 | + .listen( |
| 28 | + _controller.sink.add, |
| 29 | + ); |
| 30 | + _controller.onCancel = () { |
| 31 | + sub.cancel(); |
| 32 | + }; |
| 33 | + return _controller.stream; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +extension AbsorbErrors<T> on Stream<T> { |
| 38 | + Stream<T> absorbErrors() => transform( |
| 39 | + ErrorAbsorberTransformer(), |
| 40 | + ); |
| 41 | +} |
| 42 | + |
| 43 | +Stream<String> getNames() async* { |
| 44 | + yield 'Vandad'; |
| 45 | + await Future.delayed(const Duration(seconds: 1)); |
| 46 | + yield 'John'; |
| 47 | + await Future.delayed(const Duration(seconds: 1)); |
| 48 | + throw 'Enough names for you'; |
| 49 | +} |
| 50 | + |
| 51 | +Future<void> testIt() async { |
| 52 | + await for (final name in getNames().absorbErrors()) { |
| 53 | + name.log(); // Vandad, John, then stream closes |
| 54 | + } |
| 55 | +} |
0 commit comments