Skip to content

Instantly share code, notes, and snippets.

@adib
Created Jul 3, 2017
Embed
What would you like to do?
Simple futures/promises class for Swift
//
// CompletableFuture.swift
//
//
// Copyright 2017 Sasmito Adibowo
// http://cutecoder.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
/**
Holds the result of an asynchronous operation.
This is roughly based on Java's CompletableFuture but only implement a small subset of it.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
*/
public class CompletableFuture<PromisedType> {
var promisedObject : PromisedType?
let promiseQueue = DispatchQueue(label:"com.basilsalad.promiseCompletion")
var completionBlocks : [(_:PromisedType) -> Void]?
let completionQueue : DispatchQueue
public var canceled : Bool {
get {
var v = false
promiseQueue.sync {
guard promisedObject == nil else {
return
}
v = completionBlocks == nil
}
return v
}
}
public init(completionQueue: DispatchQueue = .global() ) {
completionBlocks = Array()
self.completionQueue = completionQueue
}
/**
Returns the promised object or nil if it doesn't exist yet.
*/
public func getNow() -> PromisedType? {
var result = nil as PromisedType?
promiseQueue.sync {
result = self.promisedObject
}
return result
}
/**
If not already completed, sets the value returned by get() and related methods to the given value.
Else does nothing.
*/
public func complete(value : PromisedType) {
promiseQueue.async {
guard let completionBlocks = self.completionBlocks,
self.promisedObject == nil else {
// already completed or canceled
return
}
self.promisedObject = value
completionBlocks.forEach({ (handler: @escaping (PromisedType) -> Void) in
self.completionQueue.async {
handler(value)
}
})
self.completionBlocks = nil
}
}
public func cancel() {
promiseQueue.async {
guard self.completionBlocks != nil else {
return
}
self.completionBlocks = nil
}
}
/**
Adds to the list of blocks to call when the value is completed.
If the promise is already completed, the block will be called immediately.
The block will be called asynchronously from the `completionQueue`.
*/
public func addCompletion(handler: (@escaping (_ :PromisedType) -> Void) ) {
promiseQueue.async {
if let value = self.promisedObject {
// already completed
self.completionQueue.async {
handler(value)
}
} else {
// enqueue
if self.completionBlocks != nil {
self.completionBlocks!.append(handler)
}
}
}
}
}
//
// CompletableFutureTest.swift
//
// Copyright 2017 Sasmito Adibowo
// http://cutecoder.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import XCTest
@testable import tvCommon
class CompletableFutureTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSingleBlockResponse() {
let testValue = NSNumber(value: 42)
let testFuture = CompletableFuture<NSNumber>()
let triggerPeriod = TimeInterval(0.1)
let completeExpectation = expectation(description: "Completion triggered")
testFuture.addCompletion { (givenValue : NSNumber) in
XCTAssertEqual(testValue, givenValue,"Given Value does not equal test value")
completeExpectation.fulfill()
}
DispatchQueue.global().asyncAfter(deadline: .now() + triggerPeriod) {
testFuture.complete(value: testValue)
}
waitForExpectations(timeout: triggerPeriod * 2, handler: nil)
}
func testTwoBlockResponse() {
let testValue = NSNumber(value: 42)
let testFuture = CompletableFuture<NSNumber>()
let triggerPeriod = TimeInterval(0.1)
let completeExpectation1 = expectation(description: "Completion 1 triggered")
testFuture.addCompletion { (givenValue : NSNumber) in
XCTAssertEqual(testValue, givenValue,"Given Value does not equal test value")
completeExpectation1.fulfill()
}
let completeExpectation2 = expectation(description: "Completion 2 triggered")
testFuture.addCompletion { (givenValue : NSNumber) in
XCTAssertEqual(testValue, givenValue,"Given Value does not equal test value")
completeExpectation2.fulfill()
}
DispatchQueue.global().asyncAfter(deadline: .now() + triggerPeriod) {
testFuture.complete(value: testValue)
}
waitForExpectations(timeout: triggerPeriod * 2, handler: nil)
}
func testCancel() {
let testFuture = CompletableFuture<NSNumber>()
let triggerPeriod = TimeInterval(0.1)
let cancelCheckDone = expectation(description: "Cancellation check done")
testFuture.addCompletion { (givenValue : NSNumber) in
XCTFail("Completion shouldn't get called. givenValue: \(givenValue)")
}
DispatchQueue.global().asyncAfter(deadline: .now() + triggerPeriod) {
testFuture.cancel()
}
DispatchQueue.global().asyncAfter(deadline: .now() + triggerPeriod * 2) {
XCTAssertTrue(testFuture.canceled, "Cancellation failed")
cancelCheckDone.fulfill()
}
waitForExpectations(timeout: triggerPeriod * 3, handler: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment