【问题标题】:Composing futures - how to get another variable associated with the result of a list of futures组合期货 - 如何获取与期货列表的结果相关联的另一个变量
【发布时间】:2013-09-18 20:36:56
【问题描述】:

我对未来的作曲有点陌生,所以我还没有弄清楚所有常见的模式。

我有一个期货列表,但我需要在创建期货时将一个名称与期货关联起来,以便以某种方式协调该列表。

EG 如果我创建一个这样的期货列表,我怎样才能让 x 与未来的结果相关联?

      val requestsForMaster = shardNames.map { x ⇒
        sentinel ? Request("SENTINEL", "get-master-addr-by-name", x)
      }

我会做这样的事情来让未来进入一个序列

      val mastersConfig = Future.sequence(requestsForMaster)
      mastersConfig.onSuccess {
        case x: List[Some[List[Some[ByteString]]]] ⇒
          self ! x.map {
            case Some(List(Some(host: ByteString), Some(port: ByteString))) ⇒    
              println("Host/port: " + host.utf8String + ":" + port.utf8String)
              Shard("name", host.utf8String, port.utf8String.toInt, None)
          }
      }

但是当我去创建 Shard 对象时,名称 (x) 不可用,我需要它。

知道如何编写这些来获得名字吗?

编辑: 这是我使用的解决方案:

  val requestsForMaster = shardNames.map { x ⇒
        (sentinel ? Request("SENTINEL", "get-master-addr-by-name", x)).map(y ⇒ (x, y))
      }

      val mastersConfig = Future.sequence(requestsForMaster)
      mastersConfig.onSuccess {
        case x: (List[(String, Some[List[Some[ByteString]]])]) ⇒
          self ! x.map {
            case (name, Some(List(Some(host: ByteString), Some(port: ByteString)))) ⇒

              println("Name Host:port: " + name + " " + host.utf8String + ":" + port.utf8String)
              Shard("name", host.utf8String, port.utf8String.toInt, None)
          }
      }

【问题讨论】:

    标签: scala akka future


    【解决方案1】:

    如果我理解正确,听起来您想在请求期货上使用map 将每个响应与分片名称配对:

    val requestsForMaster: List[Future[(String, Some[List[Some[ByteString]])] =
      shardNames.map { x =>
        val result = sentinel ? Request("SENTINEL", "get-master-addr-by-name", x)
        result.map(x -> _)
      }
    
    val mastersConfig = Future.sequence(requestsForMaster)
    
    mastersConfig.onSuccess {
      case results: List[(String, Some[List[Some[ByteString]]])] =>
        self ! results.map {
          case (x, Some(List(Some(host: ByteString), Some(port: ByteString)))) =>
            // Create the shard object.
        }
    }
    

    更一般地,如果你有一个Future[V] 和一个K,你可以通过写fv.map(k -> _) 来创建一个Future[(K, V)]

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多