I want represent external process execution as Observable[String]
, where String
- line from process output. Here example what I do, it's worked:
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable
object TestSo {
def main(args: Array[String]): Unit = {
val lineStream = scala.sys.process.Process("python3 test.py").lineStream
val lineStreamO: Observable[String] = Observable.fromIterator(Task(lineStream.iterator))
.doOnNext(l => Task(println(l))) //logging
.guarantee(Task(println("clean resources")))
println(lineStreamO.toListL.runSyncUnsafe())
}
}
You can see, that process emits new line every second. But it does not matter. Just provide full example, test.py
:
from time import sleep
print(0, flush=True)
sleep(1)
print(1, flush=True)
sleep(1)
print(2, flush=True)
sleep(1)
print(3, flush=True)
sleep(1)
print(4, flush=True)
Output:
0
1
2
3
4
5
clean resources
List(0, 1, 2, 3, 4, 5)
Problem:
I want to have timeout - if process freezes (for example sleep 100000
) process should be killed after timeout. Also if process compelted or fail, some resources should be cleaned (guarantee
in example). NonZero exit code should represent failure.
How to implement process execution as Observable[String]
with propper error handling? rx-java
solutions are welcome.