Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Boolean ops aren't as clever as they could be #5

Open
johanandren opened this issue Sep 5, 2015 · 1 comment
Open

Boolean ops aren't as clever as they could be #5

johanandren opened this issue Sep 5, 2015 · 1 comment

Comments

@johanandren
Copy link
Owner

Consider these cases:

Future { Thread.sleep(5000); false } && Future.successful(false)
Future { Thread.sleep(5000); false } || Future.successful(true)

We could make them resolve as fast as the fastest future, in best case.

@johanandren
Copy link
Owner Author

The problem is that a solution that tries to short circuit becomes a bit race conditiony and how failures are propagated becomes unclear.

Sample solution, if there is a failure in both fa and fb, which is used?

 /**
   * @return A new future that will complete with false as soon as either future completes with false
   *         or true when both futures has completed and are true.
   */
  def firstAnd(fa: Future[Boolean], fb: Future[Boolean])(implicit ec: ExecutionContext) = {
    val promise = Promise[Boolean]()

    fa.onComplete {
      case Success(false) => promise.trySuccess(false)
      case Failure(ex) => promise.tryFailure(ex)
    }
    fb.onComplete {
      case Success(false) => promise.trySuccess(false)
      case Failure(ex) => promise.tryFailure(ex)
    }
    fa.zip(fb).onComplete {
      // this is the only case that can happen after the above
      case Success((true, true)) => promise.trySuccess(true)
    }

    promise.future
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant