Skip to content

Instantly share code, notes, and snippets.

@sebastiangrail
Forked from tomj/rac_serial_requests.swift
Last active May 8, 2016 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastiangrail/929796f434be98766d547748e10d7fe0 to your computer and use it in GitHub Desktop.
Save sebastiangrail/929796f434be98766d547748e10d7fe0 to your computer and use it in GitHub Desktop.
Make 2 serial network requests with ReactiveCocoa in an Xcode Playground
import Result
import ReactiveCocoa
import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let producer1 = SignalProducer<AnyObject, NSError> { observer, disposable in
let task1 = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string:"http://jsonplaceholder.typicode.com/posts/1")!, completionHandler: { (data, response, error) in
if error != nil {
observer.sendFailed(NSError(domain:"", code:5, userInfo:nil))
} else {
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
observer.sendNext(json)
observer.sendCompleted()
}
})
task1.resume()
}
let producer2 = SignalProducer<AnyObject, NSError> { observer, disposable in
let task2 = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string:"http://jsonplaceholder.typicode.com/users/1")!, completionHandler: { (data, response, error) in
if error != nil {
observer.sendFailed(NSError(domain:"", code:5, userInfo:nil))
} else {
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
observer.sendNext(json)
observer.sendCompleted()
}
})
task2.resume()
}
producer1.flatMap(.Latest) { result -> SignalProducer<AnyObject, NSError> in
print("result from producer1 = \(result)")
return producer2
}
.start { event in
switch event {
case let .Next(value):
print("result from producer2 = \(value)")
case let .Failed(error):
print("result from producer2 = \(error)")
case .Completed:
print("Completed event")
case .Interrupted:
print("Interrupted event")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment