dart:async
庫中StreamTransformer.fromHandlers
的用法介紹如下。
用法:
StreamTransformer<S, T>.fromHandlers(
{void handleData(
S data,
EventSink<T> sink
)?,
void handleError(
Object error,
StackTrace stackTrace,
EventSink<T> sink
)?,
void handleDone(
EventSink<T> sink
)?}
)
創建一個將事件委托給給定函數的StreamTransformer。
使用複製轉換器的示例:
stringStream.transform(StreamTransformer<String, String>.fromHandlers(
handleData: (String value, EventSink<String> sink) {
sink.add(value);
sink.add(value); // Duplicate the incoming events.
}));
如果以這種方式構建的 Transformer 用於可以多次收聽的流中,則它們不能使用捕獲的狀態。
StreamController<String> controller = StreamController.broadcast();
controller.onListen = () {
scheduleMicrotask(() {
controller.addError("Bad");
controller.addError("Worse");
controller.addError("Worst");
});
};
var sharedState = 0;
var transformedStream = controller.stream.transform(
StreamTransformer<String>.fromHandlers(
handleError: (error, stackTrace, sink) {
sharedState++; // Increment shared error-counter.
sink.add("Error $sharedState: $error");
}));
transformedStream.listen(print);
transformedStream.listen(print); // Listen twice.
// Listening twice to the same stream makes the transformer share the same
// state. Instead of having "Error 1: Bad", "Error 2: Worse",
// "Error 3: Worst" as output (each twice for the separate subscriptions),
// this program emits:
// Error 1: Bad
// Error 2: Bad
// Error 3: Worse
// Error 4: Worse
// Error 5: Worst
// Error 6: Worst
相關用法
- Dart StreamTransformer.fromBind用法及代碼示例
- Dart StreamTransformer構造函數用法及代碼示例
- Dart Stream.fromFutures用法及代碼示例
- Dart StreamController用法及代碼示例
- Dart Stream.fold用法及代碼示例
- Dart Stream.map用法及代碼示例
- Dart StreamSubscription用法及代碼示例
- Dart Stream.asBroadcastStream用法及代碼示例
- Dart Stream.handleError用法及代碼示例
- Dart Stream.where用法及代碼示例
- Dart Stream.reduce用法及代碼示例
- Dart Stream.join用法及代碼示例
- Dart Stream.error用法及代碼示例
- Dart Stream.periodic用法及代碼示例
- Dart Stream.take用法及代碼示例
- Dart Stream.every用法及代碼示例
- Dart Stream.lastWhere用法及代碼示例
- Dart Stream.contains用法及代碼示例
- Dart Stream.eventTransformed用法及代碼示例
- Dart Stream.firstWhere用法及代碼示例
- Dart Stream.drain用法及代碼示例
- Dart Stream.empty用法及代碼示例
- Dart Stream.multi用法及代碼示例
- Dart Stream用法及代碼示例
- Dart Stream.distinct用法及代碼示例
注:本文由純淨天空篩選整理自dart.dev大神的英文原創作品 StreamTransformer<S, T>.fromHandlers constructor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。