I am new to scala. I am currently playing around with mongodb, akka and futures. I am trying to implement the following scenario:
there is one actor acting as a database client.
After registering the actor to the actor system, I invoke something like
dbclient ? FindAllUsers
the clients receive method looks like this
override def receive: Receive = {
case FindAllUsers => sender ! AllUsers(users.findAll)
}
where users
is an Object that looks like this:
class UserRepository(collection: MongoCollection[Document])(implicit ec: ExecutionContext)
{
def findAll: Future[Seq[String]] =
collection
.find()
.projection(fields(excludeId(), include("name")))
.map(doc => doc("name").asString.getValue)
.toFuture()
}
so, to my understanding, what is finally returned to dbclient ? FindAllUsers
is of type Future[AllUsers(Future[Seq[String]])]
. In order to print my users, I now do
implicit val ec = system.dispatcher
implicit val timeout = Timeout(1.second)
val response = dbclient ? FindAllUsers
response onComplete {
case Success(AllUsers(users)) => users onComplete {
case Success(listOfUserNames: Seq[String]) => listOfUserNames foreach println
case _ =>
}
case _ =>
}
Well, this works. But reading my response is a little bit too nested for my taste. Is there anything I don’t see here? Any way I could reduce complexity?