Today, I am going to show how to call rest API using RxSwift. Before the start, we need to know some concept in RxSwift. RxSwift is the swift implementation of popular Reactive Extensions (Rx) library created by Microsoft.
What is Reactive programming?
Reactive programming is an declarative programming paradigm concerned with data streams and the propagation of change. This means that it becomes possible to express static (e.g. arrays) or dynamic (e.g. event emitters) data streams with ease via the employed programming language(s).
— https://en.wikipedia.org/wiki/Reactive_programming.
1. Observables: is like a function with some special characters.
2.Observer: Observables produce some result according to data or action. This Result is called the Observer.
For example: .subscribe(next, error, complete)
Here subscribe is Observableandnext, error, complete are Observer.
3.DisposeBag: This is used to deinit() Observer objects from the memory.
Let start the implementation of RxSwift.
Step 1: Create a new project and pod file
Add RxSwift and RxCocoa in your pod file and install the pod.
1 2 3 4 5 6 7 |
# Podfile use_frameworks! target 'YOUR_TARGET_NAME' do pod 'RxSwift', '~> 5' pod 'RxCocoa', '~> 5' end |
Step 2: Creare a Model Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
struct countryModel: Codable { let code: Int? let result: [countryListModel]? private enum CodingKeys: String, CodingKey { case code case result } } struct countryListModel: Codable { let code: String let name: String private enum CodingKeys: String, CodingKey { case code case name } } |
Step 3: Create an API Request
Create an enum for request type which is helping to manage the API request Type.
1 2 3 |
public enum RequestType: String { case GET, POST, PUT,DELETE } |
Create a class for API Request
1 2 3 4 5 |
class APIRequest { let baseURL = URL(string: "https://api.printful.com/countries")! var method = RequestType.GET var parameters = [String: String]() } |
Configure the API request.
1 2 3 4 5 6 |
func request(with baseURL: URL) -> URLRequest { var request = URLRequest(url: baseURL) request.httpMethod = method.rawValue request.addValue("application/json", forHTTPHeaderField: "Accept") return request } |
Now calling API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class APICalling { // create a method for calling api which is return a Observable func send<T: Codable>(apiRequest: APIRequest) -> Observable<T> { return Observable<T>.create { observer in let request = apiRequest.request(with: apiRequest.baseURL) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in do { let model: countryModel = try JSONDecoder().decode(countryModel.self, from: data ?? Data()) observer.onNext( model.result as! T) } catch let error { observer.onError(error) } observer.onCompleted() } task.resume() return Disposables.create { task.cancel() } } } } |
Step 4: Create an APICalling class and DisposeBag object.
1 2 |
private let apiCalling = APICalling() private let disposeBag = DisposeBag() |
Load TableView after API call.
1 2 3 4 5 6 |
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let request = APIRequest() let result : Observable<[countryListModel]> = self.apiCalling.send(apiRequest: request) _ = result.bind(to: tableView.rx.items(cellIdentifier: "cell")) { ( row, model, cell) in cell.textLabel?.text = model.name } |
I hope it will help everyone.