-
Notifications
You must be signed in to change notification settings - Fork 1k
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
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5d64b04
Removed references to deprecated onSuccess and onFailure methods.
iwalt f31dfcc
Hard-wrapping.
iwalt e02526a
PR comments; deferred explanation of failed projection until the appr…
iwalt 532f8f1
Merge branch 'master' into deprecated-callbacks
iwalt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
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 | ||
|
@@ -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 | ||
|
@@ -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 | ||
|
@@ -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 | ||
|
@@ -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 | ||
|
@@ -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. | ||
|
@@ -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. | ||
|
||
|
@@ -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` | ||
|
@@ -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. | ||
|
@@ -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 | ||
|
@@ -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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
@@ -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() | ||
} | ||
} | ||
|
||
|
@@ -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 | ||
|
@@ -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 | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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 theFuture[Failed[Throwable]]
to aFuture[Success[Throwable]]
to allowforeach
to operate on theThrowable
, and will produce aFuture[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 theFailure[Throwable]
to aSuccess[Throwable]
and then useforeach
on the newly-successfulFuture
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 tofuture.failed.foreach
over simplygiven 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?There was a problem hiding this comment.
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 expectonFailure
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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..