Scala:链接期货,返回第一个

时间:2018-12-11 15:42:56

标签: scala future

在我有一个Future[Something]a的情况下,成功需要触发第二个Future[Unit]b。我想将ab链接在一起,但我只关心a成功。如果b失败,我可以记录一个错误并将其留在那:

到目前为止,我有:

def updateSomething(something: Something): Future[Something] = {
    val eventual: Future[Something] = repository.update(something)
    eventual.onSuccess({
      case updated =>
        repository.audit(updated.id, "Update successful")
          .onFailure({
            case throwable: Throwable => Logger.error("Audit failed", throwable)
          })
        Logger.info("Update Complete")
    })
    eventual
}

但这不会将updateaudit的生命周期联系在一起。例如,当我Await.result(service.updateSomething(...), duration)不能保证repository.audit的未来已经完成时。

3 个答案:

答案 0 :(得分:4)

select player, team, min(timeid), max(timeid) from (select lp.*, row_number() over (partition by player, team order by timeid) as seqnum, cast(cast(timeid + 1 as varchar(255)) as datetime) as yyyymm from logplayer lp ) lp group by player, team, dateadd(month, - seqnum, yyyymm) order by player, team, min(timeid); 是您的朋友。您可以使用理解+恢复:

flatMap

答案 1 :(得分:0)

您还可以使用更友好的形式:

execudeA().flatMap(a =>
  executeB().recover { case e => println(e); () }.map(_ => a)
)

答案 2 :(得分:0)

此外,您可以只使用val

val = a <- executeA()
a.andThen{ case _ => executeB(b).recover{case e => println(e)} }
a //and return a