Deploying reactive style API with RxSwift

Tram Ho

 

Perhaps most people may be familiar with API implementation using closure as a callback, today I would like to share with you how to use RxSwift to implement the API. In this article, I use Moya to build API structure, Moya as a built-in network abstraction layer with base Alamofire, which helps us simplify and clear more API structure.

https://github.com/Moya/Moya

About RxSwift

RxSwift is not new but it is not old, I have dev iOS for a relatively time, but only a few months ago I have been exposed to RxSwift and apply it to my projects. RxSwift basically, it simplifies asynchronous programming by allowing you to interact and process with data from incoming events in a sequential manner. To be honest, Rx has a wide application in many situations, but we only need to remember one thing, that Rx helps us programmatically asynchronously. If any code is asynchronous there you can apply Rx.

Code

API Structure

Using Moya, we can write very easy API structure and clear parts of it, I take an example with a simple API as follows:

and an APIProvider class, often written to MoyaProvider config.

Base Service

So we have a simple API that has been structured above, the next thing is to write the BaseService class, in both ways: normally (using closures as callbacks) and using RxSwift:

import RxSwift class ResponseError { static let invalidJSONFormat = NSError(domain: "", code: 600, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON Format"]) } class BaseService { // Cách thông thường static func requestJson(api: API, completion: @escaping ([String: Any]?, Error?) -> Void) { APIProvider.shared.request(api) { result in do { switch result { case .success(let response): let json = try response.mapJSON() if let jsonDict = json as? [String: Any] { completion(jsonDict, nil) } else { throw ResponseError.invalidJSONFormat } case .failure(let error): throw error } } catch { completion(nil, error) } } } // Sử dụng RxSwift static func requestJsonRx(api: API) -> Observable<[String: Any]> { return Observable.create({ observer -> Disposable in let request = APIProvider.shared.request(api, completion: { result in do { switch result { case .success(let response): let json = try response.mapJSON() if let jsonDict = json as? [String: Any] { observer.onNext(jsonDict) observer.onComplete() } else { throw ResponseError.invalidJSONFormat } case .failure(let error): throw error } } catch let error { observer.onError(error) observer.onComplete() } }) return Disposables.create { request.cancel() } }) } }

Child services

Let’s say we have a Book model that can be initialized from json thanks to ObjectMapper

Call API

Conclusion

I have written the usual code attached for you to have a better view, but to say that using reactive is better or the traditional way is better, I did not identify. Basically reactive is just a code style, but the problem can still be solved in many ways, those who like it hope the article will be useful for you, and those who do not like or have never used it. Can bookmark reference. Have a nice day.

Share the news now

Source : Viblo