Skip to content

Instantly share code, notes, and snippets.

@amarrella
Created November 5, 2017 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amarrella/036065eab69af2f272058e454ae262ed to your computer and use it in GitHub Desktop.
Save amarrella/036065eab69af2f272058e454ae262ed to your computer and use it in GitHub Desktop.
Timeout fs2 task
import fs2.Task
import scala.concurrent.duration.FiniteDuration
object TaskWithTimeout {
implicit class TaskWithTimeout[A](x: Task[A]) {
/**
* If the main task fails or times out, it returns the default value
*/
def timeout(default: A, duration: FiniteDuration)(implicit S:fs2.Strategy, scheduler:fs2.Scheduler):Task[A] =
fs2.Stream
.eval(x.attempt)
.mergeHaltBoth(
fs2.time.sleep_[Task](duration) ++ fs2.Stream.eval(Task.now(default)).attempt
).runLog.map(_.head.toOption.getOrElse(default))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment