[英]What is the equivalent of Kotlin's Flow.flatMapLatest in Dart Stream?
In Kotlin there is Flow.flatMapLatest()
function that:在Kotlin中有
Flow.flatMapLatest()
function :
Returns a flow that switches to a new flow produced by transform function every time the original flow emits a value.
每次原始流发出一个值时,返回一个流切换到转换 function 产生的新流。 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
? Dart 的Stream是否有等效的
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.