Below is a simple program that awaits a cancellable future. The future should evaluate to wait 20 seconds. I'm trying to demonstrate the 5.second max time bound kicking in. However, the program seems to ignore the 5.second max time bound, and waits for 20 seconds. Does anyone know why this is? Thanks
import com.github.nscala_time.time.Imports.{DateTime, richReadableInstant, richReadableInterval}
import monix.eval.Task
import monix.execution.Scheduler
import monix.execution.Scheduler.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Await
object TaskRunToFuture extends App {
def waitTwenty = {
val start = DateTime.now()
while ((start to DateTime.now()).millis < 20000) { /** do nothing */ }
}
val result = Await.result(Task.eval(waitTwenty).runToFuture, 5.seconds)
}
From Monix's Design Summary:
In your case, you've defined a Task that doesn't inherently have any "async boundaries" that would force Monix to shift to another thread, so when you call
runToFutureit ends up executingwaitTwentyon the current thread. Thus, the task has already completed by the time the Future is actually returned, soAwait.resultisn't actually called until the 20 seconds are up.See
Task#executeAsyncwhich inserts an async boundary before the task, e.g.Task.eval(waitTwenty).executeAsync.runToFutureNormally this kind of thing isn't an issue since you generally don't want to call any of the
run*methods except in your application'smain; instead you'll compose everything in terms ofTaskso your whole app is ultimately one bigTaskthat can be run, e.g. as aTaskApp.Outputs