我是scala期货的新手,我对scala期货的回报价值有疑问.
因此,scala未来的语法通常是
def downloadPage(url: URL) = Future[List[Int]] {
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何访问List[Int]调用此方法的其他方法.
换一种说法,
val result = downloadPage("localhost")
Run Code Online (Sandbox Code Playgroud)
那么List[Int]走出未来的方法应该是什么?
我尝试过使用map方法,但无法成功完成此操作
我已经阅读了有关的文档map,flatMap并且我理解它flatMap用于接受Future参数并返回另一个参数的操作Future.我不完全理解的是为什么我想这样做.举个例子:
我知道我想使用未来下载文件,但我有两个选项重新处理它:
val downloadFuture = Future { downloadFile }
val processFuture = downloadFuture map { processFile }
processFuture onSuccess { case r => renderResult(r) }
Run Code Online (Sandbox Code Playgroud)
要么
val downloadFuture = Future { // download the file }
val processFuture = downloadFuture flatMap { Future { processFile } }
processFuture onSuccess { case r => renderResult(r) }
Run Code Online (Sandbox Code Playgroud)
通过添加调试语句(Thread.currentThread().getId),我看到在两种情况下都下载,process并render发生在同一个线程中(使用ExecutionContext.Implicits.global).
我会flatMap …