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

cancel source task directly after timeout #462

Merged
merged 3 commits into from
Nov 13, 2017
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
8 changes: 4 additions & 4 deletions monix-eval/shared/src/main/scala/monix/eval/Task.scala
Original file line number Diff line number Diff line change
Expand Up @@ -939,13 +939,13 @@ sealed abstract class Task[+A] extends Serializable { self =>
* source emitting any item.
*/
def timeoutTo[B >: A](after: FiniteDuration, backup: Task[B]): Task[B] =
Task.chooseFirstOf(self, backup.delayExecution(after)).map {
Task.chooseFirstOf(self, Task.unit.delayExecution(after)).flatMap {
case Left(((a, futureB))) =>
futureB.cancel()
a
case Right((futureA, b)) =>
Task.now(a)
case Right((futureA, _)) =>
futureA.cancel()
b
backup
}

/** Creates a new `Task` by applying the 'fa' function to the successful result of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,32 @@ object TaskChooseFirstOfSuite extends BaseTestSuite {
assert(s.state.tasks.isEmpty, "backup should be canceled")
}

test("Task#timeout should not return the source after timeout") { implicit s =>
val task = Task(1).delayExecution(2.seconds).timeoutTo(1.second, Task(99).delayExecution(2.seconds))
val f = task.runAsync

s.tick()
assertEquals(f.value, None)

s.tick(3.seconds)
assertEquals(f.value, Some(Success(99)))
}

test("Task#timeout should cancel the source after timeout") { implicit s =>
val backup = Task(99).delayExecution(1.seconds)
val task = Task(1).delayExecution(5.seconds).timeoutTo(1.second, backup)
val f = task.runAsync

s.tick()
assertEquals(f.value, None)

s.tick(1.seconds)
assert(s.state.tasks.size == 1, "source should be canceled after timeout")

s.tick(1.seconds)
assert(s.state.tasks.isEmpty, "all task should be completed")
}

test("Task.chooseFirstOf(a,b) should work if a completes first") { implicit s =>
val ta = Task.now(10).delayExecution(1.second)
val tb = Task.now(20).delayExecution(2.seconds)
Expand Down