1

Im using Monix for asynchronous task workflow.

How do we kill a running Task ?

Task{ println("sleep")
      Thread.sleep(200)
      println("effect") }
.doOnCancel(Task(println("canceled")))
.timeout(100.milli) // timeout will do cancel
.runOnComplete(println)

@> Failure(java.util.concurrent.TimeoutException: Task timed-out after 100 milliseconds of inactivity) sleep canceled effect <--- what !? , task is running. Isn't it canceled !?

My current solution is ugly in my opinion(the flag checking hinders the code reusing):

var flag=true
Task{ 
      println("sleep")
      Thread.sleep(200)
      if (flag)
        println("effect") 
}
.doOnCancel(Task{ flag=false; println("canceled") })
.timeout(100.milli) // timeout will do cancel

If it is impossible, how do we kill a scheduled while not-yet-ran Task ?

My failed attempt is :

Task{ println("sleep"); Thread.sleep(200) }
.map{ _ => println("effect") }
.doOnCancel(Task(println("canceled")))
.timeout(100.milli) // timeout will do cancel
.runOnComplete(println)

Sadly it still shows the effect after the cancel happened. I hope that the scheduled and not-yet-ran Task can be canceled (the .map(...) is another Task, right?)

WeiChing 林煒清
  • 4,452
  • 3
  • 30
  • 65

2 Answers2

2

If you don't use Thread.sleep (which messes with the internals of Monix), but Task.sleep, things are working just fine.

Task
  .defer {
    println("start")
    Task.sleep(1000.millis)
  }
  .map(_ => println("effect"))
  .timeout(10.millis)
  .doOnCancel(Task(println("canceling")))

Now, the question is what's your actual use case, because I'm sure you used Thread.sleep just for illustration purposes.

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
0

I found one of solutions if it is chain of tasks:

Task{println("start");Thread.sleep(1000)}
 .asyncBoundary
 .map{_=> println("effect")}
 .doOnCancel(Task(println("canceling")))
 .timeout(10.milli)
 .executeWithOptions(_.enableAutoCancelableRunLoops)
 .runOnComplete(println)

reference: https://github.com/monix/monix/issues/226

But I hope there are easy way to interrupt task instead of using closure or split and chaining tasks.

WeiChing 林煒清
  • 4,452
  • 3
  • 30
  • 65