diff --git a/Sources/BrightFutures/Future.swift b/Sources/BrightFutures/Future.swift index b8d89ad..bbe4bec 100644 --- a/Sources/BrightFutures/Future.swift +++ b/Sources/BrightFutures/Future.swift @@ -47,6 +47,10 @@ public final class Future: Async> { public init(value: T, delay: DispatchTimeInterval) { super.init(result: .success(value), delay: delay) } + + public init(error: E, delay: DispatchTimeInterval) { + super.init(result: .failure(error), delay: delay) + } public required init(other: A) where A.Value == Value { super.init(other: other) diff --git a/Tests/BrightFuturesTests/BrightFuturesTests.swift b/Tests/BrightFuturesTests/BrightFuturesTests.swift index 310df92..e32206c 100644 --- a/Tests/BrightFuturesTests/BrightFuturesTests.swift +++ b/Tests/BrightFuturesTests/BrightFuturesTests.swift @@ -111,6 +111,29 @@ extension BrightFuturesTests { } } + func testFailedAfterFuture() { + let f = Future(error: .justAnError, delay: 1.second) + + XCTAssertFalse(f.isCompleted) + + Thread.sleep(forTimeInterval: 0.2) + + XCTAssertFalse(f.isCompleted) + + Thread.sleep(forTimeInterval: 1.0) + + XCTAssert(f.isCompleted) + + if let error = f.error { + switch error { + case .justAnError: + XCTAssert(true) + case .justAnotherError: + XCTAssert(false) + } + } + } + // this is inherently impossible to test, but we'll give it a try func testNeverCompletingFuture() { let f = Future() @@ -895,6 +918,34 @@ extension BrightFuturesTests { self.waitForExpectations(timeout: 2, handler: nil) } + func testUtilsFirstCompletedWithError() { + let futures: [Future] = [ + Future(value: 3, delay: 500.milliseconds), + Future(error: .justAnotherError, delay: 300.milliseconds), + Future(value: 23, delay: 400.milliseconds), + Future(value: 4, delay: 300.milliseconds), + Future(error: .justAnError, delay: 100.milliseconds), + Future(value: 83, delay: 400.milliseconds), + ] + + let e = self.expectation() + + futures.firstCompleted().onSuccess { _ in + XCTAssert(false) + e.fulfill() + }.onFailure { error in + switch error { + case .justAnError: + XCTAssert(true) + case .justAnotherError: + XCTAssert(false) + } + e.fulfill() + } + + self.waitForExpectations(timeout: 2, handler: nil) + } + func testUtilsSequence() { let futures = (1...10).map { fibonacciFuture($0) }