简体   繁体   English

我如何从Dart流中的回调函数产生值

[英]How can I yield a value from a callback function inside my stream in dart

I have the following stream defined in my flutter application: 我在flutter应用程序中定义了以下流:

  static Stream<String> downloadIdentifiers() async* {
    try {
      yield "test";
      final directory = await getApplicationDocumentsDirectory();

      Response response;
      Dio dio = new Dio();
      response = await dio.download(
        MyConstants.identifiersUrl,
        join(directory.path, "identifiers.json"),
        onReceiveProgress: (int received, int total) {
          print("$received / $total");
        },
      );
      yield join(directory.path, "identifiers.json");
    } catch (ex) {
      throw ex;
    }
  }

I am using https://github.com/flutterchina/dio for the download. 我正在使用https://github.com/flutterchina/dio进行下载。

I want to yield information about the download progress to my stream, but the callback on onReceiveProgress only takes a regular function as callback. 我想产生有关流下载进度的信息,但是onReceiveProgress上的回调仅将常规函数用作回调。

How can I get the information on received / total bytes to yield on my Stream? 如何获取有关流中接收/总字节数的信息?

Thank you! 谢谢!

Thanks to jamesdlin for the answer. 感谢jamesdlin的回答。 I finally did it like this with his help: 我终于在他的帮助下做到了这一点:

  static Stream<String> downloadIdentifiers() async* {
    StreamController<String> streamController = new StreamController();
    try {
      final directory = await getApplicationDocumentsDirectory();

      Dio dio = new Dio();
      dio.download(
        MyConstants.identifiersUrl,
        join(directory.path, "identifiers.json"),
        onReceiveProgress: (int received, int total) {
          streamController.add("$received / $total");
          print("$received / $total");
        },
      ).then((Response response) {
        streamController.add("Download finished");
      })
      .catchError((ex){
        streamController.add(ex.toString());
      })
      .whenComplete((){
        streamController.close();
      });
      yield* streamController.stream;
    } catch (ex) {
      throw ex;
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM