Skip to content

Removed references to deprecated onSuccess and onFailure methods. #1051

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

Merged
merged 4 commits into from
May 19, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 51 additions & 71 deletions _overviews/core/futures.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,47 +338,35 @@ a `List[String]`-- a list of recent textual posts:

The `onComplete` method is general in the sense that it allows the
client to handle the result of both failed and successful future
computations. To handle only successful results, the `onSuccess`
callback is used (which takes a partial function):
computations. In the case where only successful results need to be
handled, the `foreach` callback can be used:

val f: Future[List[String]] = Future {
session.getRecentPosts
}

f onSuccess {
case posts => for (post <- posts) println(post)
f foreach { posts =>
for (post <- posts) println(post)
}

To handle failed results, the `onFailure` callback is used:
To handle failed results, the `foreach` callback can be used on the
`Future[Throwable]` obtained via the `failed` projection (which is
explained [below](#projections)):

val f: Future[List[String]] = Future {
session.getRecentPosts
}

f onFailure {
case t => println("An error has occured: " + t.getMessage)
f.failed foreach { t =>
println("An error has occured: " + t.getMessage)
}

f onSuccess {
case posts => for (post <- posts) println(post)
f foreach { posts =>
for (post <- posts) println(post)
}

The `onFailure` callback is only executed if the future fails, that
is, if it contains an exception.

Since partial functions have the `isDefinedAt` method, the
`onFailure` method only triggers the callback if it is defined for a
particular `Throwable`. In the following example the registered `onFailure`
callback is never triggered:

val f = Future {
2 / 0
}

f onFailure {
case npe: NullPointerException =>
println("I'd be amazed if this printed out.")
}
The `failed.foreach` callback is only executed if the future fails, that
Copy link
Contributor

@giftig giftig Apr 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's technically true, but doesn't really explain what's going on. It'd be more accurate to say that future.failed converts the Future[Failed[Throwable]] to a Future[Success[Throwable]] to allow foreach to operate on the Throwable, and will produce a Future[Failure[NoSuchElementException]] if the original future succeeded, essentially swapping the position of the throwable.

I think probably the wording can just be a little simpler though, especially as there's a link to a projections anchor further down the page.

"To handle failed results, you can first use the failed projection to convert the Failure[Throwable] to a Success[Throwable] and then use foreach on the newly-successful Future instead."

I do note that the projections section clarifies that the failed projection is to enable handling exceptions with for comprehensions, though, so I wonder if there's actually an advantage to future.failed.foreach over simply

future onComplete {
  case Success(_) =>
  case Failure(t) => println("Uh oh") 
}

given that the former requires creating a new Future. Maybe it's not worth mentioning the side-effect-on-failure-only scenario at all until the projections section?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that failed.foreach doesn't really add very much (indeed if this was particularly useful then I expect onFailure wouldn't be deprecated).

So how about we just remove this failure-scenario discussion/example, replace it with your "to handle failed results" paragraph and a link to the 'Projections' section where it can be properly explained?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense to me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay so I've went a bit further to try and make things immediately obvious if the link is followed. See what you think..

is, if the original `Future` contains an exception.

Coming back to the previous example with searching for the first
occurrence of a keyword, you might want to print the position
Expand All @@ -389,16 +377,14 @@ of the keyword to the screen:
source.toSeq.indexOfSlice("myKeyword")
}

firstOccurrence onSuccess {
case idx => println("The keyword first appears at position: " + idx)
firstOccurrence onComplete {
case Success(idx) => println("The keyword first appears at position: " + idx)
case Failure(t) => println("Could not process file: " + t.getMessage)
}

firstOccurrence onFailure {
case t => println("Could not process file: " + t.getMessage)
}

The `onComplete`, `onSuccess`, and
`onFailure` methods have result type `Unit`, which means invocations
The `onComplete` and `foreach` methods both have result type `Unit`, which
means invocations
of these methods cannot be chained. Note that this design is intentional,
to avoid suggesting that chained
invocations may imply an ordering on the execution of the registered
Expand Down Expand Up @@ -427,12 +413,12 @@ text.
"na" * 16 + "BATMAN!!!"
}

text onSuccess {
case txt => totalA += txt.count(_ == 'a')
text foreach { txt =>
totalA += txt.count(_ == 'a')
}

text onSuccess {
case txt => totalA += txt.count(_ == 'A')
text foreach { txt =>
totalA += txt.count(_ == 'A')
}

Above, the two callbacks may execute one after the other, in
Expand All @@ -448,9 +434,9 @@ For the sake of completeness the semantics of callbacks are listed here:
ensures that the corresponding closure is invoked after
the future is completed, eventually.

2. Registering an `onSuccess` or `onFailure` callback has the same
2. Registering a `foreach` callback has the same
semantics as `onComplete`, with the difference that the closure is only called
if the future is completed successfully or fails, respectively.
if the future is completed successfully.

3. Registering a callback on the future which is already completed
will result in the callback being executed eventually (as implied by
Expand Down Expand Up @@ -488,38 +474,38 @@ be done using callbacks:
connection.getCurrentValue(USD)
}

rateQuote onSuccess { case quote =>
rateQuote foreach { quote =>
val purchase = Future {
if (isProfitable(quote)) connection.buy(amount, quote)
else throw new Exception("not profitable")
}

purchase onSuccess {
case _ => println("Purchased " + amount + " USD")
purchase foreach { _ =>
println("Purchased " + amount + " USD")
}
}

We start by creating a future `rateQuote` which gets the current exchange
rate.
After this value is obtained from the server and the future successfully
completed, the computation proceeds in the `onSuccess` callback and we are
completed, the computation proceeds in the `foreach` callback and we are
ready to decide whether to buy or not.
We therefore create another future `purchase` which makes a decision to buy only if it's profitable
to do so, and then sends a request.
Finally, once the purchase is completed, we print a notification message
to the standard output.

This works, but is inconvenient for two reasons. First, we have to use
`onSuccess`, and we have to nest the second `purchase` future within
`foreach` and nest the second `purchase` future within
it. Imagine that after the `purchase` is completed we want to sell
some other currency. We would have to repeat this pattern within the
`onSuccess` callback, making the code overly indented, bulky and hard
`foreach` callback, making the code overly indented, bulky and hard
to reason about.

Second, the `purchase` future is not in the scope with the rest of
the code-- it can only be acted upon from within the `onSuccess`
the code-- it can only be acted upon from within the `foreach`
callback. This means that other parts of the application do not
see the `purchase` future and cannot register another `onSuccess`
see the `purchase` future and cannot register another `foreach`
callback to it, for example, to sell some other currency.

For these two reasons, futures provide combinators which allow a
Expand All @@ -541,11 +527,11 @@ Let's rewrite the previous example using the `map` combinator:
else throw new Exception("not profitable")
}

purchase onSuccess {
case _ => println("Purchased " + amount + " USD")
purchase foreach { _ =>
println("Purchased " + amount + " USD")
}

By using `map` on `rateQuote` we have eliminated one `onSuccess` callback and,
By using `map` on `rateQuote` we have eliminated one `foreach` callback and,
more importantly, the nesting.
If we now decide to sell some other currency, it suffices to use
`map` on `purchase` again.
Expand All @@ -567,8 +553,8 @@ contains the same exception. This exception propagating semantics is
present in the rest of the combinators, as well.

One of the design goals for futures was to enable their use in for-comprehensions.
For this reason, futures also have the `flatMap`, `filter` and
`foreach` combinators. The `flatMap` method takes a function that maps the value
For this reason, futures also have the `flatMap` and `withFilter`
combinators. The `flatMap` method takes a function that maps the value
to a new future `g`, and then returns a future which is completed once
`g` is completed.

Expand All @@ -586,8 +572,8 @@ Here is an example of `flatMap` and `withFilter` usage within for-comprehensions
if isProfitable(usd, chf)
} yield connection.buy(amount, chf)

purchase onSuccess {
case _ => println("Purchased " + amount + " CHF")
purchase foreach { _ =>
println("Purchased " + amount + " CHF")
}

The `purchase` future is completed only once both `usdQuote`
Expand Down Expand Up @@ -627,13 +613,6 @@ calling `filter` has exactly the same effect as does calling `withFilter`.
The relationship between the `collect` and `filter` combinator is similar
to the relationship of these methods in the collections API.

It is important to note that calling the `foreach` combinator does not
block to traverse the value once it becomes available.
Instead, the function for the `foreach` gets asynchronously
executed only if the future is completed successfully. This means that
the `foreach` has exactly the same semantics as the `onSuccess`
callback.

Since the `Future` trait can conceptually contain two types of values
(computation results and exceptions), there exists a need for
combinators which handle exceptions.
Expand Down Expand Up @@ -688,7 +667,7 @@ the case it fails to obtain the dollar value:

val anyQuote = usdQuote fallbackTo chfQuote

anyQuote onSuccess { println(_) }
anyQuote foreach { println(_) }

The `andThen` combinator is used purely for side-effecting purposes.
It returns a new future with exactly the same result as the current
Expand Down Expand Up @@ -844,8 +823,9 @@ by the clients-- they can only be called by the execution context.
When asynchronous computations throw unhandled exceptions, futures
associated with those computations fail. Failed futures store an
instance of `Throwable` instead of the result value. `Future`s provide
the `onFailure` callback method, which accepts a `PartialFunction` to
be applied to a `Throwable`. The following special exceptions are
the `failed` projection method, which allows this `Throwable` to be
treated as the success value of another `Future`.
The following special exceptions are
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess you were trying to avoid touching the next line unnecessarily but it's made the hard-wrapping a little untidy.

treated differently:

1. `scala.runtime.NonLocalReturnControl[_]` -- this exception holds a value
Expand Down Expand Up @@ -903,8 +883,8 @@ that value. This passing of the value is done using a promise.

val consumer = Future {
startDoingSomething()
f onSuccess {
case r => doSomethingWithResult()
f foreach { r =>
doSomethingWithResult()
}
}

Expand Down Expand Up @@ -977,8 +957,8 @@ the result of that future as well. The following program prints `1`:

p completeWith f

p.future onSuccess {
case x => println(x)
p.future foreach { x =>
println(x)
}

When failing a promise with an exception, three subtypes of `Throwable`s
Expand All @@ -1001,12 +981,12 @@ Here is an example of how to do it:
def first[T](f: Future[T], g: Future[T]): Future[T] = {
val p = promise[T]

f onSuccess {
case x => p.trySuccess(x)
f foreach { x =>
p.trySuccess(x)
}

g onSuccess {
case x => p.trySuccess(x)
g foreach { x =>
p.trySuccess(x)
}

p.future
Expand Down