Last active
May 6, 2023 15:39
-
-
Save dacr/3c68bf852519566605d82345cd7256a5 to your computer and use it in GitHub Desktop.
ZIO learning - race several sub-command processes / published by https://github.com/dacr/code-examples-manager #56f16fa2-8f7e-4046-a2a5-bf19fcba2623/d713944b7e7e13444d5c30ba8844cbdf156d36f8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : ZIO learning - race several sub-command processes | |
// keywords : scala, zio, learning, process, commands, pure-functional, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 56f16fa2-8f7e-4046-a2a5-bf19fcba2623 | |
// created-on : 2022-07-20T20:24:11+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.2.2" | |
//> using dep "dev.zio::zio:2.0.13" | |
//> using dep "dev.zio::zio-process:0.7.2" | |
// --------------------- | |
import zio.* | |
import zio.process.* | |
import zio.stream.ZPipeline.{utf8Decode, splitLines} | |
object Encapsulated extends ZIOAppDefault: | |
def run = | |
for | |
process1 <- Command("vmstat", "1", "10").redirectErrorStream(true).run | |
stream1 = process1.stdout.stream.via(utf8Decode >>> splitLines) | |
outputFiber1 = stream1.runCollect | |
process2 <- Command("echo", "KO-KO-KO-KO-KO").redirectErrorStream(true).run | |
stream2 = process2.stdout.stream.via(utf8Decode >>> splitLines) | |
outputFiber2 = stream2.runCollect | |
output <- outputFiber1.raceFirst(outputFiber2).catchAll(err => ZIO.succeed(Chunk(err.toString))) | |
status1 <- process1.exitCode | |
_ <- process1.killTree.ignore | |
status2 <- process2.exitCode | |
_ <- process2.killTree.ignore | |
text = output.mkString("\n") | |
_ <- Console.printLine(s"status1 = $status1 - status2 = $status2 - Gotten content = $text") | |
yield () | |
Encapsulated.main(Array.empty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment