Finally diving intoasynchronousstandard library !
Talking aboutFuture
, the good and the bad.
Lots going on here but hopefully the comments helped breaking it down into bits size knowledge.
First of all, to useFuture
, you have to define anExecutionContext
. There are plenty of ways to do it but to stay simple, we are going to be using the defaultglobal
one.
Then, let's start with the first part. In this part, we are discoveringFuture
. Simply create then usingFuture {...}
and you can have any code in there. The return type will beFuture[A]
, whereA
is the return type of what is inside the{...}
.
You can chain futures together usingfor-comprehension, like we saw in previous episode. As well as the traditionalmap
,flatMap
, etc…
We are already encountering one danger to know aboutFuture
: they start as soon as they are created. Also, the next operation is executed when the first one return, this is why the futuresf3
tof5
are waiting on each other to start. To start them at the same time, you would have to create them outside of thefor-comprehensionlikef1
andf2
.
The second part is to illustrate the biggest danger aboutFuture
. They areNOTcancellable !
As you can see, even when theAwait
time is smaller and would throw an exception, theFuture
keep running in the background. Which can be dangerous if you are doing some insert in a database for instance and believe that it was cancel, it will not be.
Other framework more advanced likeZIOoffer better asynchronous features using Fibers instead of Threads. But this will have to wait for us to be master in functional programming and more advanced concepts before exploring this library.