當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。