Skip to main content
Version: 2.x

Migrate from Scala Future to ZIO

Introductionโ€‹

In this guide, you will move a codebase that is built on scala.concurrent.Future to ZIO without a rewrite. You wrap the Future calls you already have so that new code can be written as ZIO effects, you turn callback-style APIs into effects, you let old code that still expects a Future call your new ZIO code, and in the end you delete the wrappers.

The strategy is to work from the edges inward. Every step below leaves the program working, so you can stop after any of them and ship.

This guide covers:

This page is about the migration path. For the plain conversion functions between Future and ZIO, see How to Interop with Future?.

The Problemโ€‹

A Future starts running the moment it is created. It cannot be cancelled, it has no type for its error (the error is always a Throwable), and every operation that needs to run on a thread pool needs an implicit ExecutionContext in scope. At the end of the program, somebody has to call Await.result to get a value out.

These properties add up as a codebase grows. Timing out a call does not stop the work behind it, so slow requests keep using threads after the caller has given up. Retrying a failed call means creating a new Future by hand, because the old one has already run. Passing an ExecutionContext through every constructor and method signature is noise that has nothing to do with the business logic.

Here is a typical Future-based service. It is the starting point for this guide:

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future, TimeoutException}

final case class User(id: Int, name: String)

class UserRepo(implicit ec: ExecutionContext) {
def find(id: Int): Future[User] =
Future {
if (id == 1) User(1, "Ada") else throw new NoSuchElementException(s"no user with id $id")
}
}

object Main {
def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global
val repo = new UserRepo

try {
val name = Await.result(repo.find(1).map(_.name), 150.millis)
println(s"Hello, $name")
} catch {
case _: TimeoutException => println("timed out, but the lookup is still running")
}
}
}

A migration that rewrites everything at once is risky, because every caller of UserRepo changes with it. In this guide, you migrate one layer at a time instead.

Prerequisitesโ€‹

Add ZIO to your build:

// ZIO core
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"

Future is part of the Scala standard library, so you do not need any extra module for the interop. All the snippets below use these imports:

import zio._

import scala.concurrent.{ExecutionContext, Future}

We assume you know the basics of ZIO and how to write a ZIOAppDefault.

note

import zio._ and import scala.concurrent.duration._ both define .seconds and .millis on Int, so importing both into one file makes those calls ambiguous. In files that mix the two, import only the names you need from one of them, for example import zio.{Runtime, Task, Unsafe, ZIO}.

Mapping Future Idioms to ZIOโ€‹

The table maps the Future operations you meet most often to their ZIO counterparts. The sections after it explain the ones that need more than a rename.

FutureZIO
Future.successful(a)ZIO.succeed(a)
Future.failed(e)ZIO.fail(e)
Future(expr)ZIO.attempt(expr)
Future.fromTry(t)ZIO.fromTry(t)
future.map(f), future.flatMap(f)zio.map(f), zio.flatMap(f)
future.recover { case e => a }zio.catchSome { case e => ZIO.succeed(a) }, or zio.catchAll(e => ...)
Future.traverse(as)(f)ZIO.foreach(as)(f) (sequential) or ZIO.foreachPar(as)(f) (parallel)
Future.sequence(futures)ZIO.collectAll(effects) (sequential) or ZIO.collectAllPar(effects)
Promise[A]()Promise.make[E, A], completed with promise.succeed / promise.fail
blocking { ... }ZIO.attemptBlocking { ... }
Await.result(future, timeout)ZIOAppDefault, or Runtime.default.unsafe.run(...) at the very edge
implicit ExecutionContextnone: ZIO runs effects on its own executor (see the next section)

One difference is not visible in the table. A Future is a running computation, while a ZIO effect is a description that does nothing until it is run. For this reason ZIO.fromFuture takes a function that creates the Future, not a Future value: the Future is created every time the effect runs, which makes retries and repeats work.

Wrapping Existing Future Callsโ€‹

Start at the edges. Leave the Future-based classes as they are, and wrap each call in ZIO.fromFuture:

final case class User(id: Int, name: String)

class UserRepo(implicit ec: ExecutionContext) {
def find(id: Int): Future[User] = Future.successful(User(id, "Ada"))
}

def findUser(id: Int): Task[User] =
ZIO.fromFuture(implicit ec => new UserRepo().find(id))

ZIO.fromFuture takes a function from an ExecutionContext to a Future. The ExecutionContext that ZIO passes in is backed by ZIO's own executor, so you do not need to create or choose a thread pool for the wrapped code. If your Future code takes an ExecutionContext in its constructor or methods, hand it the one you receive. A Future that is created with a different ExecutionContext still works, but then it runs on that other pool.

The resulting Task[User] succeeds with the value of the Future, or fails with the exception that the Future fails with. Because the error type is Throwable, you can handle it with the regular ZIO error operators:

final case class User(id: Int, name: String)

def findUser(id: Int): Task[User] = ???

val greeting: Task[String] =
findUser(2)
.map(user => s"Hello, ${user.name}")
.catchSome { case e: NoSuchElementException =>
ZIO.succeed(s"fallback (${e.getMessage})")
}

The wrapper is now the only place in the new code that knows the repository returns a Future. Callers of findUser use ZIO operators, and the old Await.result goes away in the code you migrate.

Here is the Future program from the problem section, followed by its migrated version:

Run the "before" and "after" programs

Before (Future):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/future/Step1WrapAtEdges.scala
package migratefromfuture.future

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Wrapping Existing Future Calls
*
* The "before" side of migratefromfuture.Step1WrapAtEdges.
*
* sbt "migrate-from-future/runMain migratefromfuture.future.Step1WrapAtEdges"
*/
object Step1WrapAtEdges {
final case class User(id: Int, name: String)

class UserRepo(implicit ec: ExecutionContext) {
def find(id: Int): Future[User] =
Future {
if (id == 1) User(1, "Ada") else throw new NoSuchElementException(s"no user with id $id")
}
}

def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global
val repo = new UserRepo

val greeting = repo.find(1).map(user => s"Hello, ${user.name}")
println(Await.result(greeting, 5.seconds))

val fallback = repo.find(2).map(_.name).recover { case e: NoSuchElementException => s"fallback (${e.getMessage})" }
println(Await.result(fallback, 5.seconds))
}
}
sbt "migrate-from-future/runMain migratefromfuture.future.Step1WrapAtEdges"

After (ZIO):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/Step1WrapAtEdges.scala
package migratefromfuture

import zio._

import scala.concurrent.{ExecutionContext, Future}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Wrapping Existing Future Calls
*
* Replaces: Await.result(repo.find(1).map(...), 5.seconds)
* With: ZIO.fromFuture, leaving UserRepo untouched
*
* sbt "migrate-from-future/runMain migratefromfuture.Step1WrapAtEdges"
*/
object Step1WrapAtEdges extends ZIOAppDefault {
final case class User(id: Int, name: String)

// Legacy code: unchanged from the "before" program.
class UserRepo(implicit ec: ExecutionContext) {
def find(id: Int): Future[User] =
Future {
if (id == 1) User(1, "Ada") else throw new NoSuchElementException(s"no user with id $id")
}
}

// The wrapper: the only place that knows UserRepo returns a Future.
def findUser(id: Int): Task[User] =
ZIO.fromFuture(implicit ec => new UserRepo().find(id))

def run: Task[Unit] =
for {
user <- findUser(1)
_ <- Console.printLine(s"Hello, ${user.name}")
fallback <- findUser(2).map(_.name).catchSome { case e: NoSuchElementException =>
ZIO.succeed(s"fallback (${e.getMessage})")
}
_ <- Console.printLine(fallback)
} yield ()
}
sbt "migrate-from-future/runMain migratefromfuture.Step1WrapAtEdges"

Both programs print:

Hello, Ada
fallback (no user with id 2)

Interrupting a Futureโ€‹

A Future cannot be cancelled. What happens to it when the ZIO fiber that waits for it is interrupted (for example by a timeout) depends on how you wrapped it:

WrapperWhat interruption does
ZIO.fromFutureThe waiting fiber stops at once. The Future keeps running to the end.
ZIO.fromFutureInterruptThe ExecutionContext passed to your code refuses new tasks after the interruption, so the Future stops between its asynchronous steps (map, flatMap, and so on).
Fiber.fromFutureInterrupting the fiber waits until the Future has completed. A CancelableFuture is cancelled instead.

With ZIO.fromFutureInterrupt, the Future must be created with the ExecutionContext that ZIO passes in. A step that is already running, for example a blocking call, still runs to its end, because there is no way to stop a running thread. So the interruption completes when the step that was running finishes.

A pipeline of four steps, each taking 100 ms, shows the difference. Both effects below time out after 150 ms:

def pipeline(implicit ec: ExecutionContext): Future[Int] = ???

// steps 2, 3 and 4 still run after the timeout
val keepsRunning: Task[Option[Int]] =
ZIO.fromFuture(implicit ec => pipeline).timeout(Duration.fromMillis(150))

// step 2 finishes, then steps 3 and 4 never start
val stopsBetweenSteps: Task[Option[Int]] =
ZIO.fromFutureInterrupt(implicit ec => pipeline).timeout(Duration.fromMillis(150))

Fiber.fromFuture turns a Future into a Fiber[Throwable, A] that you can join, await or interrupt. It does not use an ExecutionContext of its own, because the Future is already running. Use it when you already have a started Future and want to treat it like any other fiber.

Choose ZIO.fromFutureInterrupt when the work behind the Future is expensive, because it stops the work early. Choose ZIO.fromFuture when you do not control how the Future is created.

Run the "before" and "after" programs

Before (Future):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/future/Step2Interruption.scala
package migratefromfuture.future

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future, TimeoutException}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Interruption
*
* The "before" side of migratefromfuture.Step2Interruption: a Future cannot
* be cancelled, and Await.result timing out does not stop it.
*
* sbt "migrate-from-future/runMain migratefromfuture.future.Step2Interruption"
*/
object Step2Interruption {
def step(n: Int)(implicit ec: ExecutionContext): Future[Int] =
Future {
Thread.sleep(100)
println(s" step $n done")
n
}

def pipeline(implicit ec: ExecutionContext): Future[Int] =
step(1).flatMap(_ => step(2)).flatMap(_ => step(3)).flatMap(_ => step(4))

def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global

println("waiting 150 ms for a pipeline that needs 400 ms")
try Await.result(pipeline, 150.millis)
catch { case _: TimeoutException => println("timed out, but the Future keeps running") }

Thread.sleep(500)
println("done")
}
}
sbt "migrate-from-future/runMain migratefromfuture.future.Step2Interruption"
waiting 150 ms for a pipeline that needs 400 ms
step 1 done
timed out, but the Future keeps running
step 2 done
step 3 done
step 4 done
done

After (ZIO):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/Step2Interruption.scala
package migratefromfuture

import zio._

import scala.concurrent.{ExecutionContext, Future}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Interruption
*
* Compares ZIO.fromFuture, ZIO.fromFutureInterrupt and Fiber.fromFuture when
* the waiting fiber is interrupted.
*
* sbt "migrate-from-future/runMain migratefromfuture.Step2Interruption"
*/
object Step2Interruption extends ZIOAppDefault {
def step(n: Int)(implicit ec: ExecutionContext): Future[Int] =
Future {
Thread.sleep(100)
println(s" step $n done")
n
}

def pipeline(implicit ec: ExecutionContext): Future[Int] =
step(1).flatMap(_ => step(2)).flatMap(_ => step(3)).flatMap(_ => step(4))

def run: Task[Unit] =
for {
_ <- Console.printLine("fromFuture, timeout after 150 ms")
r <- ZIO.fromFuture(implicit ec => pipeline).timeout(150.millis)
_ <- Console.printLine(s" result: $r, the Future keeps running")
_ <- ZIO.sleep(500.millis)

_ <- Console.printLine("fromFutureInterrupt, timeout after 150 ms")
r <- ZIO.fromFutureInterrupt(implicit ec => pipeline).timeout(150.millis)
_ <- Console.printLine(s" result: $r, no step starts after the interruption")
_ <- ZIO.sleep(500.millis)

_ <- Console.printLine("Fiber.fromFuture, interrupt after 150 ms")
fiber = Fiber.fromFuture(pipeline(scala.concurrent.ExecutionContext.global))
_ <- ZIO.sleep(150.millis)
_ <- fiber.interrupt
_ <- Console.printLine(" interrupt returned only after the Future completed")
} yield ()
}
sbt "migrate-from-future/runMain migratefromfuture.Step2Interruption"
fromFuture, timeout after 150 ms
step 1 done
result: None, the Future keeps running
step 2 done
step 3 done
step 4 done
fromFutureInterrupt, timeout after 150 ms
step 1 done
step 2 done
result: None, no step starts after the interruption
Fiber.fromFuture, interrupt after 150 ms
step 1 done
step 2 done
step 3 done
step 4 done
interrupt returned only after the Future completed

Turning Callback APIs into Effectsโ€‹

Many Java and older Scala libraries report their result through callbacks. In Future code you adapt them by hand with a Promise: create it, pass promise.success and promise.failure to the callbacks, and return promise.future.

In ZIO, ZIO.async does the same job. It gives you a callback function. Call it with the effect that the whole ZIO.async should produce, when the result arrives:

object PriceClient {
def fetchPrice(sku: String, onSuccess: Double => Unit, onFailure: Throwable => Unit): Unit = ???
}

def price(sku: String): Task[Double] =
ZIO.async { callback =>
PriceClient.fetchPrice(
sku,
value => callback(ZIO.succeed(value)),
error => callback(ZIO.fail(error))
)
}

The fiber that runs price is suspended until callback is called, and no thread is blocked while it waits.

If the callback API can be cancelled, use ZIO.asyncInterrupt, which lets you return an effect that cancels the request when the fiber is interrupted. See Interrupting Asynchronous Effects for a worked example.

Run the "before" and "after" programs

Before (Future):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/future/Step3Callbacks.scala
package migratefromfuture.future

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future, Promise}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Turning Callback APIs into Effects
*
* The "before" side of migratefromfuture.Step3Callbacks: a callback API
* adapted to a Future by hand with a Promise.
*
* sbt "migrate-from-future/runMain migratefromfuture.future.Step3Callbacks"
*/
object Step3Callbacks {

// A third-party client that reports its result through callbacks.
object PriceClient {
def fetchPrice(sku: String, onSuccess: Double => Unit, onFailure: Throwable => Unit): Unit = {
val thread = new Thread(() => {
Thread.sleep(50)
if (sku == "unknown") onFailure(new IllegalArgumentException(s"unknown sku: $sku"))
else onSuccess(19.99)
})
thread.setDaemon(true)
thread.start()
}
}

def price(sku: String): Future[Double] = {
val promise = Promise[Double]()
PriceClient.fetchPrice(sku, promise.success, promise.failure)
promise.future
}

def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global

println(s"price of apple: ${Await.result(price("apple"), 5.seconds)}")
val failed = price("unknown").map(_.toString).recover { case e: IllegalArgumentException => e.getMessage }
println(s"price of unknown: ${Await.result(failed, 5.seconds)}")
}
}
sbt "migrate-from-future/runMain migratefromfuture.future.Step3Callbacks"

After (ZIO):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/Step3Callbacks.scala
package migratefromfuture

import zio._

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Turning Callback APIs into Effects
*
* Replaces: Promise + promise.success / promise.failure
* With: ZIO.async
*
* sbt "migrate-from-future/runMain migratefromfuture.Step3Callbacks"
*/
object Step3Callbacks extends ZIOAppDefault {

// A third-party client that reports its result through callbacks (unchanged).
object PriceClient {
def fetchPrice(sku: String, onSuccess: Double => Unit, onFailure: Throwable => Unit): Unit = {
val thread = new Thread(() => {
Thread.sleep(50)
if (sku == "unknown") onFailure(new IllegalArgumentException(s"unknown sku: $sku"))
else onSuccess(19.99)
})
thread.setDaemon(true)
thread.start()
}
}

def price(sku: String): Task[Double] =
ZIO.async { callback =>
PriceClient.fetchPrice(
sku,
value => callback(ZIO.succeed(value)),
error => callback(ZIO.fail(error))
)
}

def run: Task[Unit] =
for {
apple <- price("apple")
_ <- Console.printLine(s"price of apple: $apple")
unknown <- price("unknown").catchSome { case e: IllegalArgumentException => ZIO.succeed(e.getMessage) }
_ <- Console.printLine(s"price of unknown: $unknown")
} yield ()
}
sbt "migrate-from-future/runMain migratefromfuture.Step3Callbacks"

Both programs print:

price of apple: 19.99
price of unknown: unknown sku: unknown

Calling ZIO from Code That Still Expects a Futureโ€‹

In a real migration, the code you migrate is called by code you do not own yet. That old code expects a Future. Give it an adapter at the boundary, and keep the adapter as thin as possible.

The tool for an adapter is Runtime.default.unsafe.runToFuture. It starts the effect on a new fiber and returns a CancelableFuture[A], which is a Future[A] with an extra cancel() method that interrupts the fiber. It is called unsafe because it runs an effect outside of ZIO, so it needs an Unsafe value in scope, which Unsafe.unsafe provides:

class PriceService {
def quote(sku: String): Task[Double] = ZIO.succeed(19.99)
}

// The adapter: the only place that turns an effect back into a Future.
class PriceServiceFutureApi(service: PriceService) {
def quote(sku: String): Future[Double] =
Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe.runToFuture(service.quote(sku))
}
}

The old callers keep calling quote and get a Future. A failure of the effect becomes a failed Future. Note that runToFuture requires the error type of the effect to be a Throwable.

When you are already inside a ZIO program and want a Future from an effect, use ZIO#toFuture. It starts the effect on a new fiber and gives you the Future as the result of an effect, so you decide where it starts:

class PriceService {
def quote(sku: String): Task[Double] = ZIO.succeed(19.99)
}

val service = new PriceService

val started: UIO[Future[Double]] = service.quote("apple").toFuture

Use runToFuture at the edge, where there is no ZIO program yet, and toFuture inside a ZIO program.

Run the "before" and "after" programs

Before (Future):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/future/Step4CallingZio.scala
package migratefromfuture.future

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Calling ZIO from Code That Still Expects a Future
*
* The "before" side of migratefromfuture.Step4CallingZio: a Future-based
* service used by a Future-based job.
*
* sbt "migrate-from-future/runMain migratefromfuture.future.Step4CallingZio"
*/
object Step4CallingZio {

class PriceService(implicit ec: ExecutionContext) {
def quote(sku: String): Future[Double] =
Future(if (sku == "unknown") throw new IllegalArgumentException(s"unknown sku: $sku") else 19.99)
}

// Code that other teams own and that still expects a Future.
class ReportJob(prices: PriceService)(implicit ec: ExecutionContext) {
def total(skus: List[String]): Future[Double] =
Future.traverse(skus)(prices.quote).map(_.sum)
}

def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global
val job = new ReportJob(new PriceService)

println(s"total: ${Await.result(job.total(List("apple", "pear")), 5.seconds)}")
println(s"failed: ${Await.result(job.total(List("apple", "unknown")).failed, 5.seconds).getMessage}")
}
}
sbt "migrate-from-future/runMain migratefromfuture.future.Step4CallingZio"

After (ZIO):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/Step4CallingZio.scala
package migratefromfuture

import zio.{Runtime, Task, Unsafe, ZIO}

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Calling ZIO from Code That Still Expects a Future
*
* Replaces: a Future-returning PriceService
* With: a ZIO service, exposed to Future callers through
* Runtime.default.unsafe.runToFuture
*
* sbt "migrate-from-future/runMain migratefromfuture.Step4CallingZio"
*/
object Step4CallingZio {

// The migrated service: no Future, no ExecutionContext.
class PriceService {
def quote(sku: String): Task[Double] =
ZIO.attempt(if (sku == "unknown") throw new IllegalArgumentException(s"unknown sku: $sku") else 19.99)
}

// The edge: the only place that turns an effect back into a Future.
class PriceServiceFutureApi(service: PriceService) {
def quote(sku: String): Future[Double] =
Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe.runToFuture(service.quote(sku))
}
}

// Code that other teams own and that still expects a Future (unchanged).
class ReportJob(prices: PriceServiceFutureApi)(implicit ec: ExecutionContext) {
def total(skus: List[String]): Future[Double] =
Future.traverse(skus)(prices.quote).map(_.sum)
}

def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global
val service = new PriceService
val job = new ReportJob(new PriceServiceFutureApi(service))

println(s"total: ${Await.result(job.total(List("apple", "pear")), 5.seconds)}")
println(s"failed: ${Await.result(job.total(List("apple", "unknown")).failed, 5.seconds).getMessage}")

// Inside ZIO code, ZIO#toFuture starts the effect on a new fiber and gives the Future back.
val viaToFuture: Future[Double] = Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe.runToFuture(service.quote("apple").toFuture)
}.flatten
println(s"via toFuture: ${Await.result(viaToFuture, 5.seconds)}")
}
}
sbt "migrate-from-future/runMain migratefromfuture.Step4CallingZio"

The "before" program prints:

total: 39.98
failed: unknown sku: unknown

The "after" program prints the same two lines, followed by one more:

total: 39.98
failed: unknown sku: unknown
via toFuture: 19.99

Removing the Wrappersโ€‹

Once the callers of a wrapper are all ZIO code, rewrite the code behind the wrapper as ZIO too, and delete the wrapper. Use the mapping table for the common operations. Two parts of the program need extra care:

  • Await.result. This is the sign that a Future program has not reached the edge yet. Make the entry point a ZIOAppDefault and let it run the effect. When there is still a Future-based caller above you, keep a single runToFuture adapter, as in the previous section.
  • ExecutionContext. Remove the implicit parameters as the classes that need them are migrated. A migrated class does not need an ExecutionContext. If a library still asks for one, ZIO.fromFuture hands you the one backed by ZIO's executor, and ZIO.executor gives you the Executor itself, which has an asExecutionContext method.
Run the "before" and "after" programs

Before (Future):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/future/Step5RemoveWrappers.scala
package migratefromfuture.future

import scala.concurrent.duration._
import scala.concurrent.{blocking, Await, ExecutionContext, Future, Promise}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Removing the Wrappers
*
* The "before" side of migratefromfuture.Step5RemoveWrappers: common Future
* idioms in one program.
*
* sbt "migrate-from-future/runMain migratefromfuture.future.Step5RemoveWrappers"
*/
object Step5RemoveWrappers {
def load(id: Int)(implicit ec: ExecutionContext): Future[String] =
Future(s"item-$id")

def main(args: Array[String]): Unit = {
implicit val ec: ExecutionContext = ExecutionContext.global

val doubled = Future.successful(21).map(_ * 2)
println(s"successful + map: ${Await.result(doubled, 5.seconds)}")

val recovered = Future.failed[Int](new RuntimeException("boom")).recover { case _: RuntimeException => 0 }
println(s"failed + recover: ${Await.result(recovered, 5.seconds)}")

val traversed = Future.traverse(List(1, 2, 3))(load)
println(s"traverse: ${Await.result(traversed, 5.seconds)}")

val sequenced = Future.sequence(List(load(4), load(5)))
println(s"sequence: ${Await.result(sequenced, 5.seconds)}")

val blockingCall = Future(blocking { Thread.sleep(50); "slept" })
println(s"blocking: ${Await.result(blockingCall, 5.seconds)}")

val promise = Promise[String]()
Future(promise.success("completed by another future"))
println(s"promise: ${Await.result(promise.future, 5.seconds)}")
}
}
sbt "migrate-from-future/runMain migratefromfuture.future.Step5RemoveWrappers"

After (ZIO):

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/Step5RemoveWrappers.scala
package migratefromfuture

import zio._

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Removing the Wrappers
*
* Replaces: Future combinators, Promise, blocking and Await.result
* With: the matching ZIO operators, with no Future left in the program
*
* sbt "migrate-from-future/runMain migratefromfuture.Step5RemoveWrappers"
*/
object Step5RemoveWrappers extends ZIOAppDefault {
def load(id: Int): UIO[String] =
ZIO.succeed(s"item-$id")

def run: Task[Unit] =
for {
doubled <- ZIO.succeed(21).map(_ * 2)
_ <- Console.printLine(s"successful + map: $doubled")

recovered <- ZIO.fail(new RuntimeException("boom")).catchSome { case _: RuntimeException => ZIO.succeed(0) }
_ <- Console.printLine(s"failed + recover: $recovered")

traversed <- ZIO.foreachPar(List(1, 2, 3))(load)
_ <- Console.printLine(s"traverse: $traversed")

sequenced <- ZIO.collectAllPar(List(load(4), load(5)))
_ <- Console.printLine(s"sequence: $sequenced")

blockingCall <- ZIO.attemptBlocking { Thread.sleep(50); "slept" }
_ <- Console.printLine(s"blocking: $blockingCall")

promise <- Promise.make[Nothing, String]
_ <- promise.succeed("completed by another fiber").fork
value <- promise.await
_ <- Console.printLine(s"promise: $value")
} yield ()
}
sbt "migrate-from-future/runMain migratefromfuture.Step5RemoveWrappers"

Both programs print the same results. The last line differs only in the word that names who completed the promise (future or fiber):

successful + map: 42
failed + recover: 0
traverse: List(item-1, item-2, item-3)
sequence: List(item-4, item-5)
blocking: slept
promise: completed by another fiber

Putting It Togetherโ€‹

The complete example below is a migrated order-summary program. Two legacy pieces stay as they are and are wrapped once each: a Future-returning repository (with ZIO.fromFutureInterrupt) and a callback-based price client (with ZIO.async). The business logic is plain ZIO, the lookups run in parallel with ZIO.foreachPar, and the entry point is a ZIOAppDefault:

zio-examples/migrate-from-future/src/main/scala/migratefromfuture/CompleteExample.scala
package migratefromfuture

import zio._

import scala.concurrent.{ExecutionContext, Future}

/*
* Guide: Migrate from Scala Future to ZIO
* Section: Putting It Together
*
* A migrated order-summary program. Two legacy pieces stay as they are and are
* wrapped once each: a Future-returning repository (ZIO.fromFutureInterrupt)
* and a callback-based price client (ZIO.async). Everything else is ZIO, and
* the entry point is a ZIOAppDefault, so there is no Await.result left.
*
* sbt "migrate-from-future/runMain migratefromfuture.CompleteExample"
*/
object CompleteExample extends ZIOAppDefault {

final case class Order(id: Int, sku: String, quantity: Int)

// Legacy: Future-returning repository (unchanged).
class OrderRepo(implicit ec: ExecutionContext) {
def find(id: Int): Future[Order] =
Future {
Thread.sleep(50)
if (id > 0 && id < 100) Order(id, s"sku-$id", id) else throw new NoSuchElementException(s"no order $id")
}
}

// Legacy: callback-based price client (unchanged).
object PriceClient {
def fetchPrice(sku: String, onSuccess: Double => Unit, onFailure: Throwable => Unit): Unit = {
val thread = new Thread(() => {
Thread.sleep(50)
onSuccess(10.0)
})
thread.setDaemon(true)
thread.start()
}
}

// The two wrappers: the only code that knows about Future and callbacks.
def findOrder(id: Int): Task[Order] =
ZIO.fromFutureInterrupt(implicit ec => new OrderRepo().find(id))

def price(sku: String): Task[Double] =
ZIO.async { callback =>
PriceClient.fetchPrice(sku, value => callback(ZIO.succeed(value)), error => callback(ZIO.fail(error)))
}

// Migrated business logic: plain ZIO.
def orderTotal(id: Int): Task[Double] =
for {
order <- findOrder(id)
unit <- price(order.sku)
} yield unit * order.quantity

def run: Task[Unit] =
for {
totals <- ZIO.foreachPar(List(1, 2, 3))(orderTotal)
_ <- Console.printLine(s"totals: $totals")
missing <- orderTotal(500).catchSome { case e: NoSuchElementException =>
ZIO.succeed(s"skipped: ${e.getMessage}")
}
_ <- Console.printLine(missing)
slow <- orderTotal(4).timeout(10.millis)
_ <- Console.printLine(s"with a 10 ms timeout: $slow")
} yield ()
}

It prints:

totals: List(10.0, 20.0, 30.0)
skipped: no order 500
with a 10 ms timeout: None

Running the Examplesโ€‹

Clone the repository and change into the examples module. Every step above ships as two runnable programs: the Future original under migratefromfuture.future.* and its ZIO migration under migratefromfuture.*. Run both and compare their output:

git clone https://github.com/zio/zio.git
cd zio/zio-examples/migrate-from-future
sbt "runMain migratefromfuture.CompleteExample"

Going Furtherโ€‹

ZIO Chat

๐Ÿ”ฅ Ignite your ZIO journey with ZIO Chat! ๐Ÿ”ฅ Ready to unravel the intricacies of ZIO? As your trusty sidekick, I'm here to light the way. No matter if you're wandering through functional forests or traversing effectful landscapes, I've got answers to keep you on track. Your ZIO adventure starts here โ€“ ask me anything and let's explore together!