如何在Dart中使用新的Streams API执行stdin.close()? [英] How can I do stdin.close() with the new Streams API in Dart?

查看:339
本文介绍了如何在Dart中使用新的Streams API执行stdin.close()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求用户在我的命令行(dart:io)应用程序中输入。在我得到用户的回答后,我想取消订阅 Stream 。然后,我可能想再听一遍(但使用不同的监听器,因此 pause() resume()

 

code> cmdLine = stdin
.transform(new StringDecoder());

后来,当我想收集输入时:

  cmdLineSubscription = cmdLine.listen((String line){
try {
int optionNumber = int.parse(line);
if > = 1&&&< = option< = choiceList.length){
cmdLineSubscription.cancel();
completer.complete(choiceList [optionNumber -1] .hash);
} else {
throw FormatException(Number outside the range。);
}
} on FormatException catch(e){
print(Input a number between 1 and $ {choiceList.length},please。);
}
});

这样工作原理,但它留下 stdin 在程序执行结束时打开。使用之前的API,关闭 stdin 就像调用 stdin.close()一样简单。但是使用新的API, stdin Stream ,那些没有关闭方法。



我认为我在做的是关闭(读取:取消订阅)转换后的流, stdin)流开放。



我是否正确?如果是,我如何在程序退出时关闭底层的 stdin 流?

解决方案

要关闭 stdin ,您只需取消订阅:

  cmdLineSubscription.cancel(); 

这是等效的方式。所以你的直觉是对的。我不知道我是否理解这个问题 - 这个方法有问题吗?


I ask user for input in my command line (dart:io) app. After I get my answer from the user, I want to unsubscribe from the Stream. Then, later, I may want to listen to it again (but with different listener, so pause() and resume() don't help me).

On startup, I have this:

cmdLine = stdin
          .transform(new StringDecoder());

Later, when I want to gather input:

cmdLineSubscription = cmdLine.listen((String line) {
  try {
    int optionNumber = int.parse(line);
    if (optionNumber >= 1 && optionNumber <= choiceList.length) {
      cmdLineSubscription.cancel();
      completer.complete(choiceList[optionNumber - 1].hash);
    } else {
      throw new FormatException("Number outside the range.");
    }
  } on FormatException catch (e) {
    print("Input a number between 1 and ${choiceList.length}, please.");
  }
});

This works as intended, but it leaves stdin open at the end of program execution. With the previous API, closing stdin was as easy as calling stdin.close(). But with the new API, stdin is a Stream, and those don't have the close method.

I think that what I'm doing is closing (read: unsubscribing from) the transformed stream, but leaving the raw (stdin) stream open.

Am I correct? If so, how can I close the underlying stdin stream on program exit?

解决方案

To close stdin, you just unsubscribe from it:

cmdLineSubscription.cancel();

This is the equivalent way of doing it. So your intuition was right. I'm not sure if I understood the question -- was there a problem with this approach?

这篇关于如何在Dart中使用新的Streams API执行stdin.close()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆