Scala on Android with scala.concurrent.Future do n

2019-08-06 13:33发布

问题:

We build an android application with Scala 2.11. We use scala.concurrent.Future for async background tasks. The problem is, that we do not see any exceptions in logcat if exceptions are thrown inside a Future block.

We already create an execution context with our own reporter:

lazy val reporter: (Throwable => Unit) = {
    t =>
      t.printStackTrace()
  }

  implicit lazy val exec = ExecutionContext.fromExecutor(
    new ThreadPoolExecutor(10, 100, 5, TimeUnit.MINUTES,
      new LinkedBlockingQueue[Runnable]), reporter)

Even if I set a breakpoint inside the reporter the debugger does never stop here, even if I force throwing of exceptions insde a Future {...} block. What are we doing wrong

回答1:

According to your comment it looks like you simply didn't work with Future as needed. When some exception occurred during the Future computation it is transformed into Failure case (like Failure from Try, but in async context), e.g:

scala> Future { 10 / 0 }
res21: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@24f3ffd

As you can see there is no exception thrown or printed. To handle this exception you need to use callbacks, i.e onComplete or onFailure, e.g:

scala> res21.onFailure { case error => println(s"Error: ${ error.getMessage }") }
Error: / by zero

A great intro into Futures and Duality was given by the man with psychedelic T-Shirt Erik Meijer in the coursers intro to Reactive Programming.



标签: android scala