【问题标题】:How i get Boolean From a Future[Settings]我如何从未来获得布尔值[设置]
【发布时间】:2019-08-09 15:19:10
【问题描述】:

我有一个从 getProductSettingsMethod 返回的 Future [ProductSettings]。现在我需要 clearCanLoad 字段中的真假

   def getEmployerProductSettingsQuery(employer: Employer): DBIOAction[ProductSettings, NoStream, Effect.Read] = {
val productSettingsQ = productSettingsQuery.filter(_.employerId === employer.id).result
productSettingsQ.map(_.headOrServerException(s"Could not find ProductSettings for employer ${employer.id}"))
 }

   def getEmployerProductSettings(employer: Employer): Future[ProductSettings] =
db.run(getEmployerProductSettingsQuery(employer))

我尝试了 .map、filter、flatMap 等,但都没有工作

def cleared (employer : Employer) :Boolean = {
val f : Future[ProductSettings] = 
 getEmployerProductSettings(employer)

  val iscleared: Boolean = f.filter { x =>
    x.clearedCanLoadSpenditCards match {
      case true =>
        true
      case false =>
        false
    }
  }

}

这不起作用也不起作用是过滤器

val f : Future[ProductSettings] = getEmployerProductSettings(employer)

     val iscleared  = f . 
  .filter(_.clearedCanLoadSpenditCards.equals(true)).equals(true)

case class ProductSettings(id: Long,
                       employerId: Long,
                       enableCard: Boolean,
                       enableLt: Boolean,
                       enableLtRefundDays: Boolean,
                       enableLtConversion: Boolean,
                       enableLtOPayment: Boolean,
                       clearedCanLoad: Boolean,
                       clearedAt:Option[LocalDateTime]) {

equals true 应该返回布尔值,但我得到一个 Future[Boolean] 返回。我如何提取布尔值

【问题讨论】:

  • 如果可能你应该返回Future[Boolean]并将调用代码修改为mapFuture以访问其中的Boolean
  • 你能格式化你的代码吗?看书太难了

标签: scala dictionary filter


【解决方案1】:

Future 的主要目的是异步执行代码。阻止未来从中获取价值违背了它的目的。但是如果你真的需要 cleared 方法来返回 Boolean 你可以阻塞未来直到它的值被解析。

您可以使用Await

import scala.concurrent.duration._

val result: ProductSettings = scala.concurrent.Await.result(f, 1 second)

这将等待未来解决。如果第二次通过并且f 仍未解决,则会抛出TimeoutException

scala.concurrent.Await#result

【讨论】:

  • 而不是IllegalArgumentException,如果指定的atMost等待时间已经过去,则应该是TimeoutException
  • Await(如var)只能在没有其他解决方案的情况下使用。而是作曲。
  • @leo 你说得对。我相应地更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多