Scala Future - for understanding, synchronizing mixes and asynchronous

In my method1, I need to asynchronously call another method2 that returns Option (result1). Than if result1 is empty, I need to call another method3 asynchronously, but if result1 is not empty, I just need to return it.

Here is a way:

  def signIn(username: String): Future[User] = {
    for {
      foundUser <- userService.findByUsername(username) // this method returns Future[Option[User]], 
      // foundUser is Option[User]
      user <- if (foundUser.isEmpty) {
        val newUser = User(username = "User123")
        userService.create(newUser).map(Some(_)) // this method returns Future[Option[User]]
      }
      else
        // Here I want to return just foundUser, of course, it is not possible. 
        // IS THIS APPROACH CORRECT?? DOES THIS LINE CREATE ASYNCHRONOUS CALL?          
        Future.successful(foundUser)
    } yield user 
  }

Question:

Future.successful(foundUser)Is this approach correct in the code above? Does this line create an asynchronous call? If so, how can this be avoided? I already selected foundUser asynchronously, and I do not want the additional asynchronous call to return the already selected value.

+4
source share
2 answers

Future.successful ExecutionContext. Promise[T] Future[T]:

/** Creates an already completed Future with the specified result.
   *
   *  @tparam T       the type of the value in the future
   *  @param result   the given successful value
   *  @return         the newly created `Future` instance
   */
  def successful[T](result: T): Future[T] = Promise.successful(result).future

Option.fold:

def signIn(username: String): Future[User] = 
  userService
    .findByUsername(username)
    .flatMap(_.fold(userService.create(User(username = "User123")))(Future.successful(_))
+4

@ , flatMap , . :

def signIn(username: String): Future[User] =
  userService.findByUsername(username)
    .flatMap {
      case Some(user) => Future.successful(user)
      case _ => userService.create(User(username = "User123"))
    }
+1

Source: https://habr.com/ru/post/1652110/


All Articles