Skip to content

Instantly share code, notes, and snippets.

@vinhnx
Created August 20, 2019 08:31
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 vinhnx/47df68a8e12b66fe712bbd5f65b70f13 to your computer and use it in GitHub Desktop.
Save vinhnx/47df68a8e12b66fe712bbd5f65b70f13 to your computer and use it in GitHub Desktop.
Simple RxSwift's usage of Single for async network events
enum GitHubAPIError: Error {
case userIsEmpty
case invalidData
}
func fetchGithubUser(_ user: String) -> Single<[String: Any]> {
guard user.isEmpty == false else { return Single.error(GitHubAPIError.userIsEmpty) }
return Single<[String: Any]>.create(subscribe: { completion in
let task = URLSession.shared
.dataTask(with: URLRequest(url: URL(string: "https://api.github.com/users/\(user)")!), completionHandler: { data, _, error in
if let error = error { return completion(.error(error)) }
guard let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
return completion(.error(GitHubAPIError.invalidData))
}
return completion(.success(json))
})
task.resume()
return Disposables.create {
task.cancel()
}
})
}
fetchGithubUser("vinhnx").subscribe { event in
switch event {
case .success(let response):
print(response)
case .error(let failure):
print(failure)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment