Last active
July 8, 2019 15:20
-
-
Save darrensapalo/711d33b3e7f59b712ea3b6d5406952a4 to your computer and use it in GitHub Desktop.
Swift 3 example of a network request wrapped as an RxSwift Observable and converted into a class object
This file contains hidden or 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 Foundation | |
import RxSwift | |
let networkQueue = DispatchQueue(label: "com.appName.networkQueue") | |
class Queue { | |
var name: String | |
public init (_ name: String) { | |
self.name = name | |
} | |
} | |
class SomeViewController { | |
private var queues = BehaviorSubject<[Queue]>(value: []) | |
private var disposeBag = DisposeBag() | |
func onButtonPress() { | |
getQueue() | |
.subscribeOn(ConcurrentDispatchQueueScheduler(queue: networkQueue)) | |
.observeOn(MainScheduler.instance) | |
.subscribe(queues.asObserver()) | |
.addDisposableTo(disposeBag) | |
} | |
func viewDidLoad() { | |
getQueue() | |
.subscribeOn(ConcurrentDispatchQueueScheduler(queue: networkQueue)) | |
.observeOn(MainScheduler.instance) | |
.bindTo(tableView.rx.items(cellIdentifier: "Cell")) { index, model, cell in | |
cell.textLabel?.text = model | |
} | |
.addDisposableTo(disposeBag) | |
} | |
func getQueue() -> Observable<[Queue]> { | |
return Observable.create { observer in | |
// The network query wrapped as an Observable<Data> | |
let performNetworkQuery : Observable<Data> = Observable.create { obx in | |
let url = "http://myapi.myserver.com/queues" | |
let request = URLRequest(url: URL(string: url)!) | |
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in | |
do { | |
guard error == nil else { | |
throw error! | |
} | |
guard let data = data else { | |
throw RxError.unknown | |
} | |
obx.onNext(data) | |
obx.onCompleted() | |
} catch(let error) { | |
obx.onError(error) | |
} | |
}) | |
task.resume() | |
return Disposables.create { | |
task.cancel() | |
} | |
} | |
// Functional definition of acquiring queue data from the network to your class objects | |
// Perform network query | |
return performNetworkQuery | |
// Begin the sequence in the background thread | |
.subscribeOn(ConcurrentDispatchQueueScheduler(queue: networkQueue)) | |
// Convert the data into an array of queues represented as a JSON object | |
.map { (data: Data) -> [[String: Any]] in | |
return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String: Any]] | |
} | |
// Transform each element of the array | |
.flatMap { (array: [[String : Any]]) -> Observable<[String: Any]> in | |
return Observable.from(array) | |
} | |
// Into a String | |
.map { (dictionary: [String : Any]) -> String in | |
return dictionary["name"] as? String ?? "" | |
} | |
// And turn it into a Queue | |
.map(Queue.init) | |
// We want all of it | |
.toArray() | |
.subscribe(observer) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment