【问题标题】:How to get out value from Scala Future onComplete/onSuccess如何从 Scala Future onComplete/onSuccess 中获取价值
【发布时间】:2017-08-02 10:03:05
【问题描述】:

我的代码具有如下高级结构。这只是一个复制高层结构的例子。:-

import scala.concurrent.Future


class FutureReturnsAValue extends PersonAgeModifier {
  def main(args: Array[String]) {

    val jhonObj = Person("Jhon", 25)

    val punishmentResult = addAgeCurse(jhonObj)
    println("The punishment result for Jhonny is " + punishmentResult)

  }

  def addAgeCurse(person: Person): String = {

    val oldAge = person.age
    val futureAge = LongProcessingOpForAge(person)
    futureAge.onSuccess {

      newAge =>

        if (newAge = oldAge + 5) {
          "screw the kiddo, he aged by 5 years" // somehow return this string
        }

        else {
          "lucky chap, the spell did not affect him" // somehow return this string
        }
    }

  }
}

class PersonAgeModifier {

  def LongProcessingOpForAge(person: Person): Future[Int] = {
    Future.successful {
      person.age + 5
    }
  }
}


case class Person
(
  val name: String,
  var age: Int

)

object Person {
  def apply(name: String, age: Int) = new Person(name, age)

}

所以我的要求是:- 我需要 addAgeCurse() 方法中的字符串。现在我知道你可能会建议将未来值 LongProcessingOpForAge() 这样传递给 main() ,但这不是我想要的。

问题:

  1. 获取字符串并将其传递给 main() 的最简洁方法是什么。 (通过 clean ,我的意思是不涉及使用等待 x 持续时间,因为我想避免任何手动干预。)

谢谢

【问题讨论】:

  • 你将不得不等待未来在某个地方完成。您可以更改函数以返回未来并在主函数中等待,或者在函数中等待。
  • 或者撰写而不是等待
  • @cchantep,如何在这里撰写帮助。您能否提供更多信息。谢谢
  • 试图从Future 中“提取”纯/同步值正在消除任何并发/并行/线程优势。而是继续“在内部”工作
  • 是的,不要出去。留在!也不要println,这只会弄乱他们的终端。

标签: scala future


【解决方案1】:

也许你要求:

scala> import concurrent._, ExecutionContext.Implicits._
import concurrent._
import ExecutionContext.Implicits._

scala> def f = Future(42)
f: scala.concurrent.Future[Int]

scala> def g = f.map(_ + 1)
g: scala.concurrent.Future[Int]

scala> :pa
// Entering paste mode (ctrl-D to finish)

object Main extends App {
  for (i <- g) println(i)
}

// Exiting paste mode, now interpreting.

defined object Main

scala> Main main null
43

这是阻止您的答案的简单成语。主线程在拥有它之前不会退出。使用map 转换未来值。

【讨论】:

    猜你喜欢
    • 2014-05-29
    • 2022-10-24
    • 2019-02-07
    • 2017-08-01
    • 2021-05-30
    • 2021-01-18
    • 2018-03-06
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多