Skip to content

Instantly share code, notes, and snippets.

@vasily-kirichenko
Last active September 30, 2018 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasily-kirichenko/9f59d7e067330af6d5b0440158608242 to your computer and use it in GitHub Desktop.
Save vasily-kirichenko/9f59d7e067330af6d5b0440158608242 to your computer and use it in GitHub Desktop.
def processor(account: String, taskCh: MVar[Int]): Observable[String] =
Observable.fromAsyncStateAction[Unit, String](_ =>
for {
task <- taskCh.take
// simulate real processing by an async sleep
_ <- Task.sleep(Random.nextInt(500).millis)
} yield {
println(s"[$account] processed $task")
((task + 100).toString, ())
}
)()
val (taskCh, processors) =
Await.result(
MVar.empty[Int]
.map(ch => (ch, List("acc1", "acc2").map(account => processor(account, ch))))
.runAsync,
Duration.Inf)
val cancelSource =
Observable.range(0, 10)
.dump("source")
.mapParallelUnordered(processors.length) { task =>
taskCh.put(task.toInt)
}
.dump("mapParallel")
.subscribe()
val stream =
Observable
.merge(processors: _*)
.consumeWith(Consumer.foreach(x => println(s"consumed $x")))
Await.result(stream.runAsync, 5.seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment