Created
December 15, 2016 11:51
-
-
Save mishagray/ebda61ada5a6a3835ca2760735b0450b to your computer and use it in GitHub Desktop.
DefferedFuture.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import FutureKit | |
private var startPromiseHandler = ExtensionVarHandler() | |
public extension Future { | |
fileprivate var startPromise : Promise<Void>? { | |
set(p) { | |
startPromiseHandler.setValueOn(self, value: p) | |
} | |
get { | |
return startPromiseHandler.getValueFrom(self) | |
} | |
} | |
public func start() throws { | |
if let p = self.startPromise { | |
p.completeWithSuccess(()) | |
} | |
else { | |
throw FutureKitError(genericError: "deferUsing was not called on this future's promise") | |
} | |
} | |
} | |
extension Promise { | |
public func deferUsing<C: CompletionType>(_ onStartHandler: @escaping () throws -> C) where C.T == T { | |
let startPromise = Promise<Void>() | |
startPromise.future.onComplete { result in | |
switch result { | |
case .success: | |
self.complete(try onStartHandler().completion) | |
case .cancelled: | |
self.completeWithCancel() | |
case let .fail(error): | |
self.completeWithFail(error) | |
} | |
} | |
self.future.startPromise = startPromise // retain loop issues? | |
} | |
public func deferUsing(_ onStartHandler: @escaping () throws -> T) { | |
self.deferUsing { () -> Completion<T> in | |
return .success(try onStartHandler()) | |
} | |
} | |
} | |
func returnDefferred() -> Future<Int> { | |
let p = Promise<Int>() | |
p.deferUsing { () -> Future<Int> in | |
return Executor.background.execute { | |
return 5 | |
} | |
} | |
return p.future | |
} | |
func checkDeffered() throws { | |
let f = self.returnDefferred().onSuccess { val in | |
print(val) | |
} | |
try f.start() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment