In Kotlin there is Flow.flatMapLatest()
function that:
Returns a flow that switches to a new flow produced by transform function every time the original flow emits a value. When the original flow emits a new value, the previous flow produced by transform block is cancelled.
Is there an equivalent function for Dart 's Stream
?
Nothing existing, but it should be fairly easy to write.
import "dart:async";
extension StreamExpandLatest<S> on Stream<S> {
Stream<T> expandLatest<T>(Stream<T> expand(S value)) {
var result = StreamController<T>(sync: true);
result.onListen = () {
StreamSubscription<T>? current;
StreamSubscription<S> sourceSubscription = this.listen((S data) {
current?.cancel();
try {
current = expand(data).listen(result.add, onError: result.addError);
} catch (e, s) {
result.addError(e, s);
}
}, onError: (Object e, StackTrace s) {
current?.cancel();
result.addError(e, s);
}, onDone: () {
current?.cancel();
result.close();
});
result
..onPause = () {
sourceSubscription.pause();
current?.pause();
}
..onResume = () {
current?.resume();
sourceSubscription.resume();
}
..onCancel = () {
current?.cancel();
sourceSubscription.cancel();
};
};
return result.stream;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.