Skip to content

Instantly share code, notes, and snippets.

@luizmb
Created August 7, 2018 20:12
Show Gist options
  • Save luizmb/d869eaae8114c2312c81f0a02b4fce56 to your computer and use it in GitHub Desktop.
Save luizmb/d869eaae8114c2312c81f0a02b4fce56 to your computer and use it in GitHub Desktop.
Pointfree Parallel Playground test
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct Promise<A> {
let subscribe: (@escaping (A) -> Void) -> Void
}
extension Promise {
func map<B>(_ f: @escaping (A) -> B) -> Promise<B> {
return Promise<B> { callbackB in
self.subscribe { a in
let b = f(a)
callbackB(b)
}
}
}
func flatMap<B>(_ f: @escaping (A) -> Promise<B>) -> Promise<B> {
return Promise<B> { callbackB in
self.subscribe { a in
let promiseB = f(a)
promiseB.subscribe { b in
callbackB(b)
}
}
}
}
}
func zip2<A, B>(_ fa: Promise<A>, _ fb: Promise<B>) -> Promise<(A, B)> {
return Promise<(A, B)> { callback in
let group = DispatchGroup()
var a: A?
var b: B?
group.enter()
fa.subscribe {
a = $0
group.leave()
}
group.enter()
fb.subscribe {
b = $0
group.leave()
}
group.notify(queue: .main) {
callback((a!, b!))
}
}
}
func delay(by duration: TimeInterval, line: UInt = #line, execute: @escaping () -> Void) {
print("delaying line \(line) by \(duration)")
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
execute()
print("executed line \(line)")
}
}
let p1 = Promise { callback in
delay(by: 2) {
callback(42)
}
}
.flatMap { int in
Promise { callback in
delay(by: 1.5) {
callback(String.init(int))
}
}
}
let p2 = Promise { callback in
delay(by: 1.5) {
callback(43)
}
}
.flatMap { int in
Promise { callback in
delay(by: 0.5) {
callback(String.init(int))
}
}
}
zip2(p1, p2).subscribe {
dump($0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment