zmeda
zmeda

Reputation: 2909

Using scala + akka to generate unique ID

Let me first explain my problem a little bit. I ahve a repository which stores all the known IDs. And this repository is an actor, let call him repo. I definied GetId(id: Id) message and GetIdReply(Option[Id]) in this actor in order to request for specific id and get reply back if it already exists or no. Pretty straight forward I'd say.

Now I have another actor which is responsible for generating an unique ID. So I tried to implement this function like:

private def getUniqueId(): Id = {
  implicit val timeout = Timeout(500.millis)
  var id = Id(UUID.randomUUID().toString)
  val getIdReply = repo ? GetId(Id)
  getIdReply.mapTo[GetIdReply] onSuccess {
    case success =>
      success.id match {
        case Some(matchedId) =>
          // Generated ID already exists, let's call this function recursively
          id = getUniqueId
        case None =>
          // Generated ID is OK
      }
  }
  id
}

I tried to implement this as a recursion and this thing works only if the generated ID is unique on first attempt. On second and all the other attempts it doesn't work. So my question here is how to properly construct such a function that will "loop" until ID is really unique?

Thx!

Best

Upvotes: 0

Views: 1947

Answers (1)

wingedsubmariner
wingedsubmariner

Reputation: 13667

Because your result depends on communicating with an actor, your function must return a Future:

private def getUniqueId(): Future[Id] = {
  implicit val timeout = Timeout(500.millis)
  val id = Id(UUID.randomUUID().toString)
  repo ? GetId(id) flatMap {
    case GetIdReply(Some(_)) => getUniqueId()
    case GetIdReply(None) => Future.successful(id)
  }
}

Upvotes: 2

Related Questions