【发布时间】:2014-04-18 00:11:54
【问题描述】:
问题来了,我有一个库,它有一个阻塞方法返回 Try[T]。但由于它是阻塞的,我想使用 Future[T] 使它成为非阻塞的。在未来的块中,我还想计算一些取决于源阻塞方法的返回值的东西。
但是如果我使用类似下面的东西,那么我的 nonBlocking 将返回 Future[Try[T]] 不太令人信服,因为 Future[T] 已经可以代表 Failure[U],我宁愿将异常传播到Future[T] 是自我。
def blockMethod(x: Int): Try[Int] = Try {
// Some long operation to get an Int from network or IO
throw new Exception("Network Exception") }
}
def nonBlocking(x: Int): Future[Try[Int]] = future {
blockMethod(x).map(_ * 2)
}
这是我尝试过的,我只是在future {} 块中使用.get 方法,但我不确定这是否是最好的方法。
def blockMethod(x: Int): Try[Int] = Try {
// Some long operation to get an Int from network or IO
throw new Exception("Network Exception") }
}
def nonBlocking(x: Int): Future[Int] = future {
blockMethod(x).get * 2
}
这是正确的方法吗?还是有一种更 scala 惯用的方式将 t Try[T] 转换为 Future[T]?
【问题讨论】:
标签: scala