Rafa
Rafa

Reputation: 3339

Returning value from a Scala Future

In the below code, I'm trying to do two operations. One, to create a customer in a db, and the other, to create an event in the db. The creation of the event, is dependent on the creation of the user.

I'm new to Scala, and confused on the role of Futures here. I'm trying to query a db and see if the user is there, and if not, create the user. The below code is supposed to check if the user exists with the customerByPhone() function, and if it doesn't, then go into the createUserAndEvent() function.

What it's actually doing, is skipping the response from customerByPhone and going straight into createUserAndEvent(). I thought that by using a flatmap, the program would automatically wait for the response and that I wouldn't have to use Await.result is that not the case? Is there a way to avoid using Await.result to not block the thread on production code?

override def findOrCreate(phoneNumber: String, creationReason: String): Future[AvroCustomer] =  {
  //query for customer in db
  //TODO this goes into createUserAndEvent before checking that response comes back empty from querying for user
  customerByPhone(phoneNumber)
    .flatMap(_ => createUserAndEvent(phoneNumber, creationReason, 1.0))
}

Upvotes: 0

Views: 67

Answers (1)

Matt Fowler
Matt Fowler

Reputation: 2723

You don't need to use Await.result or any other blocking. You do in fact have the result from customerByPhone, you're just ignoring it with the _ . I think what you want is something like this:

customerByPhone(phoneNumber)
  .flatMap(customer => {
    if(customer == null)
      createUserAndEvent(phoneNumber, creationReason, 1.0)
    else
      Future(customer)
   })

You need to code the logic to do something only if the customer isn't there.

Upvotes: 2

Related Questions