当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Dart StreamTransformer.fromHandlers用法及代码示例


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.dev大神的英文原创作品 StreamTransformer<S, T>.fromHandlers constructor。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。