Scala Future

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 defaultglobalone.

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], whereAis 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 futuresf3tof5are waiting on each other to start. To start them at the same time, you would have to create them outside of thefor-comprehensionlikef1andf2.

The second part is to illustrate the biggest danger aboutFuture. They areNOTcancellable !

As you can see, even when theAwaittime is smaller and would throw an exception, theFuturekeep 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.

Reveal more information and clues
Load Exercise