Skip to content

Instantly share code, notes, and snippets.

@satishbabariya
Last active March 17, 2023 05:38
Show Gist options
  • Save satishbabariya/d33473809326a73a586f195fe7cc4972 to your computer and use it in GitHub Desktop.
Save satishbabariya/d33473809326a73a586f195fe7cc4972 to your computer and use it in GitHub Desktop.
Simple RxSwift API Call
func getTodos() -> Observable<Any> {
// If No Internet Connection Throws error
// if Reachability()!.connection == .none {
// // !!!! return data form cache here
// return Observable.error(RESTError(message: "No internet connection.", type: .warning))
// }
return Observable.create { (observer) -> Disposable in
Alamofire.request("https://jsonplaceholder.typicode.com/todos", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: ["Content-Type": "application/json"])
.responseData { response in
switch response.result {
case let .success(data):
do {
observer.onNext(data)
observer.onCompleted()
} catch {
observer.onError(error)
}
case let .failure(error):
observer.onError(error)
}
}
return Disposables.create()
}
}
@satishbabariya
Copy link
Author

Function call:

getTodos().subscribe({ [weak self] response in
                guard let self = self else {
                    return
                }
                 switch response {
                case let .next(data):
                    // data
                case let .error(error):
                   // error
                case .completed:
                    break
                }
            }).disposed(by: disposeBag)
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment