-
-
Save sebastiangrail/929796f434be98766d547748e10d7fe0 to your computer and use it in GitHub Desktop.
Make 2 serial network requests with ReactiveCocoa in an Xcode Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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