Dart Stream的listen()没有调用onDone

时间:2014-01-22 18:23:18

标签: dart dart-io

我有一个带变换器的流,它将UTF8.decoder融合到LineSplitter。它工作得很好,但从不调用onDone参数中指定的函数。

import 'dart:async';
import 'dart:io';
import 'dart:convert';

void main(List<String> arguments) {

  Stream<List<int>> stream = new File("input.txt").openRead();

  stream.transform(UTF8.decoder.fuse(const LineSplitter()))
      .listen((line) {
        stdout.writeln(line);            
      }, onDone: () {
          stdout.write("done");
      }).asFuture().catchError((_) => print(_));
}

为什么永远不会被召唤的任何想法?

1 个答案:

答案 0 :(得分:6)

import 'dart:async';
import 'dart:io';
import 'dart:convert';

void main(List<String> arguments) {

  Stream<List<int>> stream = new File("input.txt").openRead();

  stream.transform(UTF8.decoder.fuse(const LineSplitter()))
      .listen((line) {
        stdout.writeln(line);
      }, onDone: () {
          stdout.write("done");
      }); //.asFuture().catchError((_) => print(_));
}
/**
   * Returns a future that handles the [onDone] and [onError] callbacks.
   *
   * This method *overwrites* the existing [onDone] and [onError] callbacks
   * with new ones that complete the returned future.
   *
   * In case of an error the subscription will automatically cancel (even
   * when it was listening with `cancelOnError` set to `false`).
   *
   * In case of a `done` event the future completes with the given
   * [futureValue].
   */
  Future asFuture([var futureValue]);

返回处理[onDone]和[onError]回调的未来。

此方法使用新的覆盖现有的 [onDone] 和[onError]回调,以完成返回的未来。

所以,回答:

import 'dart:async';
import 'dart:io';
import 'dart:convert';

void main(List<String> arguments) {

  Stream<List<int>> stream = new File("input.txt").openRead();

  stream.transform(UTF8.decoder.fuse(const LineSplitter()))
      .listen((line) {
        stdout.writeln(line);
      }, onDone: () {
          stdout.write("Not wait me, because 'asFuture' overwrites me");
      }).asFuture().catchError((_) => print(_))
      .whenComplete(() => stdout.write("done"));
}