我正在尝试编写以下函数
def haltOnUserInput[O](process: Process[Task, O]): Process[Task, O]
当用户在process
上发送一行时停止stdin
。在这种情况下,可以在结束流程本身之前等待流程中的当前计算结束。
我尝试了以下内容:
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scalaz.{ -\/, \/-, \/ }
import scalaz.stream._
import scalaz.concurrent.Task
def haltOnUserInput[O](process: Process[Task, O]): Process[Task, O] = {
process.either(io.stdInLines).flatMap {
case -\/(o) => Process.emit(o)
case \/-(_) => println("here"); Process.halt
}
}
我正在测试:
scala> val oneSec = scala.concurrent.duration.Duration("1s")
oneSec: scala.concurrent.duration.Duration = 1 second
scala> val test = haltOnUserInput(Process.awakeEvery(oneSec)).take(10).map(_.toString).to(io.stdOutLines).run
test: scalaz.concurrent.Task[Unit] = scalaz.concurrent.Task@7a5e41bb
scala> test.run
1000144294 nanoseconds
2000148316 nanoseconds
here
3000130736 nanoseconds
here
4000124898 nanoseconds
5000189134 nanoseconds
6000201269 nanoseconds
here
7000127797 nanoseconds
8000132194 nanoseconds
9000191001 nanoseconds
10000126974 nanoseconds
如您所见,用户输入已确认(“此处”已打印多次)但过程未中断。我不确定flatMap
是否符合预期wrt Process.halt
。
如何正确编写haltOnUserInput
?
答案 0 :(得分:4)
另一个解决方案是使用wye.interrupt:
val input = io.stdInLines.take(1).map(_ => true)
val dory = Process.awakeEvery(1.second).map(_ => println("Hi!"))
val process = input.wye(dory)(wye.interrupt)
process.run.run
答案 1 :(得分:1)
这是我实现的haltOnUserInput:
def haltOnUserInput[O](process: Process[Task, O]): Process[Task, O] = {
val stop = Process.constant(()) either io.stdInLines map (_.isRight)
process.until(stop)
}