Akka:向Actor发送一个Future消息

14

我在一个Actor中有以下代码

def receive = {
    case All() => {
        val collection: BSONCollection = db("ping")
        val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
        val zender = sender
        future onComplete {
            case Success(list) => zender ! list
            case Failure(throwable) => zender ! List()
        }
    }
}

我不喜欢使用 onComplete 函数将结果发送回发件人 actor。我想知道是否有可能将其转换为以下形式:

def receive = {
    case All() => {
        val collection: BSONCollection = db("ping")
        val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
        "sender ! future" // one option
        "future.map( list => sender ! list)" //Another option. I know it's not map, but maybe another function        
    }
}

我觉得使用future chaining更加流畅。


你的第一种方法不起作用吗? - Incerteza
@Alex 是的,但管道更加优雅。 - Luciano
好的。但是你说“我不喜欢必须使用onComplete函数将结果发送回发件人actor”,而你的代码确实做到了这一点——你正在将结果发送回发件人actor。 - Incerteza
2个回答

32

您可以使用管道模式来实现这一点。只需 import akka.pattern.pipe,然后就能够使用 future pipeTo actor 将消息从 futures 管道传递到 actors 中。


10

如果在出现错误时想要得到一个空列表,您可能需要将“recover”和“pipeTo”的调用链接起来。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接