Skip to content

Instantly share code, notes, and snippets.

@tomj
Last active May 22, 2016 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomj/73a9a0370671dff09ecb53e727e4dea7 to your computer and use it in GitHub Desktop.
Save tomj/73a9a0370671dff09ecb53e727e4dea7 to your computer and use it in GitHub Desktop.
Make 2 serial network requests with ReactiveCocoa in an Xcode Playground (with changes from @sebastiangrail)
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")
}
}
/**
Console:
result from producer1 = {
body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto";
id = 1;
title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit";
userId = 1;
}
result from producer2 = {
address = {
city = Gwenborough;
geo = {
lat = "-37.3159";
lng = "81.1496";
};
street = "Kulas Light";
suite = "Apt. 556";
zipcode = "92998-3874";
};
company = {
bs = "harness real-time e-markets";
catchPhrase = "Multi-layered client-server neural-net";
name = "Romaguera-Crona";
};
email = "Sincere@april.biz";
id = 1;
name = "Leanne Graham";
phone = "1-770-736-8031 x56442";
username = Bret;
website = "hildegard.org";
}
Completed event
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment