func fetchEvents(repo: String) {
let response = Observable.from([repo])
.map { urlString -> URL in
return URL(string: "https://api.github.com/repos/\(urlString)/events")!
}
.map { url -> URLRequest in
return URLRequest(url: url)
}
.flatMap { request -> Observable<(response: HTTPURLResponse, data: Data)> in
return URLSession.shared.rx.response(request: request) // this method returns 'Observable'
// completes whevever your app receive the full response form the web server.
}
.share(replay: 1) // Finally, to allow more subscriptions to the result of the web request, chain one last operator. You will use share(replay:, scope:) to share the observable and keep in a buffer the last emitted event:
response
.filter { response, _ in
return 200 ..< 300 ~= response.statusCode
}
.compactMap { _, data -> [Event]? in // lets through any non-nil values ( filters any nils )
// discard the response object and take only the response data
return try? JSONDecoder().decode([Event].self, from: data) // attempt to decode the response data as an array of Events.
// use a try? to return a nil value in case the decoder throws an error while decoding the JSON data.
}
.subscribe(onNext: { [weak self] newEvents in
self?.processEvents(newEvents)
})
.disposed(by: bag)
// flatMap -> return Observable<(response: HTTPURLResponse, data: Data)>
// map -> return Observable<Observable<(response: HTTPURLResponse, data: Data)>>