Skip to Content
Mastering Functional Programming
book

Mastering Functional Programming

by Anatolii Kmetiuk
August 2018
Intermediate to advanced
380 pages
10h 2m
English
Packt Publishing
Content preview from Mastering Functional Programming

Constructing asynchronous tasks

IO provides an API that allows you to transform an existing computation based on callbacks into an asynchronous IO. This can be used to port existing computation to IO in an asynchronous manner.

Suppose you have the following computation:

def taskHeavy(name: String): Int = {  Thread.sleep(1000)  println(s"${Thread.currentThread.getName}: " +    s"$name: Computed!")  42}

Like we saw previously, it is blocking a thread as it uses Thread.sleep to block the computation. The entire point of the computation is that it does not return immediately.

Now, let's take a look at how you can asynchronously run the computation:

def sync(name: String): IO[Int] =  IO { taskHeavy(name) }

Here, we are using an already familiar ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Functional Programming

Learning Functional Programming

Jack Widman

Publisher Resources

ISBN: 9781788620796Supplemental Content