retryWhen<T> method
- Stream<
T> streamFactory( - Stream<
void> retryWhenFactory(- dynamic error,
- StackTrace stack
Creates a Stream that will recreate and re-listen to the source Stream when the notifier emits a new value. If the source Stream emits an error or it completes, the Stream terminates.
If the retryWhenFactory
emits an error a RetryError will be
thrown. The RetryError will contain all of the Errors and
StackTraces that caused the failure.
Basic Example
RetryWhenStream<int>(
() => Stream<int>.fromIterable(<int>[1]),
(dynamic error, StackTrace s) => throw error,
).listen(print); // Prints 1
Periodic Example
RetryWhenStream<int>(
() => Stream<int>
.periodic(const Duration(seconds: 1), (int i) => i)
.map((int i) => i == 2 ? throw 'exception' : i),
(dynamic e, StackTrace s) {
return Rx.timer('random value', const Duration(milliseconds: 200);
},
).take(4).listen(print); // Prints 0, 1, 0, 1
Complex Example
bool errorHappened = false;
RetryWhenStream(
() => Stream
.periodic(const Duration(seconds: 1), (i) => i)
.map((i) {
if (i == 3 && !errorHappened) {
throw 'We can take this. Please restart.';
} else if (i == 4) {
throw 'It\'s enough.';
} else {
return i;
}
}),
(e, s) {
errorHappened = true;
if (e == 'We can take this. Please restart.') {
return Stream.value('Ok. Here you go!');
} else {
return Stream.error(e);
}
},
).listen(
print,
onError: (e, s) => print(e),
); // Prints 0, 1, 2, 0, 1, 2, 3, RetryError
Implementation
static Stream<T> retryWhen<T>(
Stream<T> Function() streamFactory,
Stream<void> Function(dynamic error, StackTrace stack) retryWhenFactory,
) =>
RetryWhenStream<T>(streamFactory, retryWhenFactory);