Created
August 20, 2019 08:31
-
-
Save vinhnx/47df68a8e12b66fe712bbd5f65b70f13 to your computer and use it in GitHub Desktop.
Simple RxSwift's usage of Single for async network events
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
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