在Scala中,如何在两个连续期货之间共享数据?

时间:2016-01-28 03:01:19

标签: scala

我想在两个顺序执行的期货之间分享数据。这是我的代码草稿:

def deleteRecord(request: DeleteRequest): TwitterFuture[domain.Response] = {
    lazy val fn = {

      repository.findById(request.id).map { record: Option[TableRecord] =>
        val data = Map[String,Any](
            "id" -> String.valueOf(request.id),
            "study" -> String.valueOf(request.study),
            "associate" -> String.valueOf(record.get.associate),
            "role" -> String.valueOf(record.get.role)
          )
      }.flatMap { _ =>
        repo.delete(request.id).map { rowsAffected: Int =>
          /* audit study associate deletion */
          val event = audit(AuditEventType.RecordDeleted, principal.get, data)
          pipelineService.logEvent(topicSettings.database, event)

          domain.Response(status = Status.Created, data = Seq(rowsAffected))
        }
      }
    }

    secure(principal.get, fn)
  }

具体来说,我希望event块中的repo.delete能够访问data块中的findById地图。

我基于https://stackoverflow.com/a/25057306/3195691的顺序期货实施。

1 个答案:

答案 0 :(得分:2)

您需要将该值作为您未来的结果,或者换句话说您应该将其返回。只是声明一个变量不会使该块返回它 - 它只能在其声明范围内保持可访问状态。

生成/返回结果的f1示例和使用它的f2

import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration._

scala> val f1 = Future(1)
f1: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@538f7b25

scala> val f2 = f1.flatMap { v1 => Future(v1 + 2) }
f2: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@28d364fd

scala> val res = Await.result(f2, 2 seconds) // just to show the result, don't use Await!
res: Int = 3

在您的示例中,findById似乎返回Future[Option[TableRecord]]。如果是这样,那么将您的代码更改为:

repository.findById(request.id).map { record: Option[TableRecord] =>
        Map[String,Any](
            "id" -> String.valueOf(request.id),
            "study" -> String.valueOf(request.study),
            "associate" -> String.valueOf(record.get.associate),
            "role" -> String.valueOf(record.get.role)
        )
      }.flatMap { data => //... use `data` here

map返回的未来类型为Future[Map[String,Any]],传递给data的{​​{1}}类型为flatMap