Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove race condition in Scheduler.effect.delayCancellable #1078

Merged
merged 1 commit into from
Feb 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions core/jvm/src/test/scala/fs2/SchedulerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,16 @@ class SchedulerSpec extends AsyncFs2Spec {
assert(r == Vector(3, 6))
}
}

"delay cancellable: cancel after completion is no op" in {
val s = mkScheduler
.evalMap { s =>
s.effect.delayCancellable(IO.unit, 20.millis).flatMap(t => t._1 <* t._2)
}

runLogF(s).map { r =>
r.head shouldBe Some(())
}
}
}
}
6 changes: 4 additions & 2 deletions core/shared/src/main/scala/fs2/Scheduler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -274,18 +274,20 @@ object Scheduler extends SchedulerPlatform {
/**
* Starts a timer for duration `d` and after completion of the timer, evaluates `fa`.
* Returns a "gate" value which allows semantic blocking on the result of `fa` and an action which cancels the timer.
* If the cancellation action is invoked, the gate completes with `None`. Otherwise, the gate completes with `Some(a)`.
* If the cancellation action is invoked before the timer completes, the gate completes with `None`. Otherwise, the
* gate completes with `Some(a)`.
*/
def delayCancellable[F[_], A](fa: F[A], d: FiniteDuration)(
implicit F: Effect[F],
ec: ExecutionContext): F[(F[Option[A]], F[Unit])] =
async.promise[F, Option[A]].flatMap { gate =>
F.delay {
// needs to be a val, executes the task
val cancel = scheduler.scheduleOnce(d) {
ec.execute(() =>
async.unsafeRunAsync(fa.flatMap(a => gate.complete(Some(a))))(_ => IO.unit))
}
gate.get -> (F.delay(cancel()) *> gate.complete(None))
gate.get -> (F.delay(cancel()) *> gate.complete(None).handleError(_ => ()))
}
}

Expand Down