Skip to content

Instantly share code, notes, and snippets.

@EfraimB
Created November 22, 2018 11:49
Show Gist options
  • Save EfraimB/3ac240fc6e65aa8835df073f68fe32d9 to your computer and use it in GitHub Desktop.
Save EfraimB/3ac240fc6e65aa8835df073f68fe32d9 to your computer and use it in GitHub Desktop.
PromiseKit (6.4.1) CancellablePromise
//
// Promise + CancelRequest.swift
// PeopleFinders
//
// Created by Efraim Budusan on 12/13/17.
// Copyright © 2017 Tapptitude. All rights reserved.
//
import Foundation
import PromiseKit
import Tapptitude
public protocol TTCancellable: class {
func cancel()
}
class PromiseCancelledError: CancellableError {
var isCancelled: Bool {
return true
}
}
public class CancellablePromise<T>:TTCancellable, Thenable, CatchMixin {
var promise:Promise<T>!
var resolver:Resolver<T>!
var cancellable:TTCancellable!
init(resolver: ((Resolver<T>) throws ->())!, cancellable:TTCancellable) {
self.promise = Promise<T>.init(resolver: { (_resolver) in
self.resolver = _resolver
try resolver(_resolver)
})
self.cancellable = cancellable
}
init(promise:Promise<T>, resolver:Resolver<T>, cancellable:TTCancellable ) {
self.promise = promise
self.resolver = resolver
self.cancellable = cancellable
}
public func cancel() {
guard promise.isPending else {
return
}
self.resolver.reject(PromiseCancelledError())
cancellable?.cancel()
}
var value:T? {
return promise.value
}
public func pipe(to: @escaping (PromiseKit.Result<T>) -> Void) {
self.promise.pipe(to: to)
}
public var result: PromiseKit.Result<T>? {
return self.promise.result
}
public func _map<U>( _ transform: @escaping (T) throws -> U) -> CancellablePromise<U> {
return CancellablePromise<U>.init(resolver: { (_resolver) in
self.pipe(to: { (result) in
_resolver.resolve(result.map(transform))
})
}, cancellable: self.cancellable)
}
}
extension PromiseKit.Result {
func map<U>(_ transform: @escaping (T) throws -> U) -> PromiseKit.Result<U> {
switch self {
case .fulfilled(let value):
do {
let mappedValue = try transform(value)
return PromiseKit.Result<U>.fulfilled(mappedValue)
} catch (let error) {
return PromiseKit.Result<U>.rejected(error)
}
case .rejected(let error):
return PromiseKit.Result<U>.rejected(error)
}
}
}
@calmh
Copy link

calmh commented Mar 19, 2021

Hi! You linked to this from StackOverflow, but I see it's copyright with "all rights reserved" and no license, so we cannot use this? Is it intended to instead be in the public domain or have a specific license attached?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment