我有一个名为Gate
的Akka Actor,它用Open
或Closed
的响应消息来回答Status
消息:
"A stateless gate" must {
"be open" in {
val parent = TestProbe()
val gate = parent.childActorOf(
TestStatelessGate.props(7)
)
gate ! 7
gate ! Gate.Status
parent.expectMsg(Gate.Open)
}
我想做的是构造一个逻辑AND门,它查询一个门列表,如果它们都是打开的,则返回Open
:
"A logical AND gate" must {
"be open when all children are open" in {
val parent = TestProbe()
val parent2 = TestProbe()
val gate_1 = parent.childActorOf(
TestStatelessGate.props(7)
)
val gate_2 = parent.childActorOf(
TestStatelessGate.props(5)
)
val gate_list = List(gate_1, gate_2)
val and_gate = parent2.childActorOf(
LogicalAndGate.props(gate_list)
)
gate_1 ! 7
gate_2 ! 5
and_gate ! Gate.Status
parent2.expectMsg(Gate.Open)
Scala文档中有一些关于使用for
表达式和pipe
的内容。该文档的相关部分是:
final case class Result(x: Int, s: String, d: Double)
case object Request
implicit val timeout = Timeout(5 seconds) // needed for `?` below
val f: Future[Result] =
for {
x <- ask(actorA, Request).mapTo[Int] // call pattern directly
s <- actorB.ask(Request).mapTo[String] // call by implicit conversion
d <- (actorC ? Request).mapTo[Double] // call by symbolic name
} yield Result(x, s, d)
f.pipeTo(actorD
我在尝试使用ActorRef列表执行类似的操作时遇到了问题(下面的代码中为gate_list
):
override def receive: Receive = {
case Status => {
val futures: Seq[Future[Any]] =
for (g <- gate_list)
yield ask(g, Status)
val all_open: Future[Boolean] = Future {
!futures.contains(Closed)
}
pipe(all_open) to parent
}
}
当然,这是行不通的,因为futures.contains(Closed)
比较的是两种不同类型的东西,一个Future[Any]
和我的case对象。
1条答案
按热度按时间t5fffqht1#
我假设
Open
和Closed
是case object
的值,它们继承了OpenClosed
的一些公共特性。首先,你需要使用
mapTo
将ask
的结果转换为OpenClosed
。我也会使用map
而不是for
:然后,您需要
Future.sequence
来等待所有这些操作完成: