Skip to content

Instantly share code, notes, and snippets.

@geoHeil
Last active October 22, 2019 10:41
Show Gist options
  • Save geoHeil/580518df9b3c8b5a978e736af757ac21 to your computer and use it in GitHub Desktop.
Save geoHeil/580518df9b3c8b5a978e736af757ac21 to your computer and use it in GitHub Desktop.
import monix.eval.Task
import monix.execution.Cancelable
import monix.execution.cancelables.CompositeCancelable
import scala.util.{Failure, Success, Try}
object Foo extends App {
val things = Range(1, 10)
val c = CompositeCancelable()
implicit val scheduler = monix.execution.Scheduler.global
val futures = things.map(e => {
val f = t(e)
(f, Cancelable(()=> {
f // TODO ref to f?
println("canceled")
}))
})
// TODO how can the futures be added here / made cancellable?
futures.foreach(f=> c += f._2)
def t(i: Int) = Task.eval {
// Try { // not using a try it at least fails & stops, but I want to also cancel the other tasks
Thread.sleep(1000)
val result = i + 1
if (result > 5) {
throw new Exception("asdf")
}
// i.e. write to file, that's why unit is returned
println(result) // Effect
"Result"
// }
}
futures.foreach(f=> {
})
futures.par.foreach(_._1.runToFuture.onComplete {
case Success(value) =>
println(value)
case Failure(ex) =>
c.cancel
System.err.println(ex)
println("stopping with error")
System.exit(1)
})
}
@geoHeil
Copy link
Author

geoHeil commented Oct 22, 2019

How can the futures be added here / made cancellable?

Not using a try it at least fails & stops, but I want to also cancel the other tasks.

Is it good to manually call the futures in parallel?

@geoHeil
Copy link
Author

geoHeil commented Oct 22, 2019

When including:

futures.foreach(f=> c += f._2)

The result is:

4
2
5
3
Result
Result
Result
Result
java.lang.Exception: asdf
stopping with error
java.lang.Exception: asdf
stopping with error
java.lang.Exception: asdf
stopping with error
Process finished with exit code 1

I.e. a cancel is not performed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment