How to simplify the data layer with MoyaRx and Codable
Tags: agilewebandappde, iosdeveloper, mobileapp
Published: 2018-07-19 06:45:58

---
title: How to simplify the data layer with MoyaRx and Codable
published: true
tags: Agile web and app de,iOS Developer,mobile app
canonical_url: https://apiumhub.com/tech-blog-barcelona/data-layer-with-moyarx-and-codable/
---

Today all apps are connected at some point with servers to show data. This is why it is very important to have a well defined (and simple) client implementation to avoid problems in this very important layer of the application. We will also look at a pattern widely used in REST services and how we can improve it using the latest tools provided by Rx and Swift. In [Apiumhub](/) we decided to write an article about how to simplify the data layer with MoyaRx and Codable and we hope you find it useful! 

 

## Data layer with MoyaRx and Codable

 

### Data model

For the data model, it is very common to use a constructor from a dictionary [String: Any]. There are libraries like _SwiftyJSON_ that facilitate the use of dictionaries, in our case we choose to use “guard let” to access the values in a secure manner.

[![guard let](https://apiumhub.com/wp-content/uploads/2018/07/mobile.png)](https://apiumhub.com/wp-content/uploads/2018/07/mobile.png)

 

### Repository

The repository layer is responsible for encapsulating the calls of the REST client. In the following code, Alamofire is used as a REST client. This library is widely used to abstract and facilitate calls to web services. Alamofire uses Apple’s NSURLSession api internally.

[![Alamofire](https://apiumhub.com/wp-content/uploads/2018/07/2.png)](https://apiumhub.com/wp-content/uploads/2018/07/2.png)

 

## Improving the REST layer with Codable and Moya

One of the objectives we had was to simplify the components involved in this layer. Having an initializer in each model was expensive and prone to errors. Avoid using failover initializers. On the other hand, the repository returns a complete closure with two optional values that must be checked in the upper layer, usually the service.

 

### Model with Codable

One of the novelties of Swift 4 was the introduction of Codable. The Codable protocol is a typealias of the combination of the existing _Encodable_ and _Decodable protocols_

[![Encodable and Decodable protocols](https://apiumhub.com/wp-content/uploads/2018/07/3.png)](https://apiumhub.com/wp-content/uploads/2018/07/3.png)

This protocol facilitates the coding and decoding of data, all you have to do is implement it in our data models. Native types and collections of Codable types are already implemented by default, in the case of creating own types, they should also implement the protocol. In the following code we see how to make the Product model implement Codable.

[![Codable](https://apiumhub.com/wp-content/uploads/2018/07/4.png)](https://apiumhub.com/wp-content/uploads/2018/07/4.png)

_Codable_ allows us to define the value of the keys in which it will be encoded or decoded with the enumerated _CodingKeys_. This list must be exhaustive for all the properties of the structure. If you omit any property of the model in the enumerated CodingKeys, it will not be taken into account at the time of coding or decoding this model.

By using Codable we saved the initializer [![initializer](https://apiumhub.com/wp-content/uploads/2018/07/5.png)](https://apiumhub.com/wp-content/uploads/2018/07/5.png)

###  

### Repository using Moya

Moya is a library that acts as an abstraction of the data layer that internally uses _Alamofire_ to make the _REST request_. Moya provides many functionalities as:

- **Targets:** Enumerated with all the specification of the endpoints in a typed way.
- **Plugins:** These are classes that implement the _PluginType_ protocol that have different methods that are executed when making an HTTP request. Among other things, they allow us to intercept the requests and modify or log information.
- **EndpointClosures:** allows you to modify the endpoints that have been defined in the Target.
- **StubClosure:** allows returning stubs for requests, acting as a fake server.

Moya has a reactive extension called MoyaRx that allows encapsulating the response of a request in an Observable of Rx. In the following code, we see how MoyaRx is used in the previous repository implementation.

[![MoyaRx](https://apiumhub.com/wp-content/uploads/2018/07/6.png)](https://apiumhub.com/wp-content/uploads/2018/07/6.png)

 

## Conclusions: data layer with MoyaRx and Codable

- We have reduced the amount of productive code both in the repository and in the models thus eliminating the need to test them.
- The parsing is now done using the operator **– map (d: Decodable)**. This operator receives any type that conforms to the _Decodable_ protocol and returns an observable with the object mapped, if it fails somewhere, we will receive an exception with detailed information about what the reason was.
- The repository now returns an observable of _Product_, we can apply any type of transformation on the result using the Rx operators.
- If a request is made, we will receive an observable with events of the type of the response, on the other hand, if it fails, an _error_ event that we can be recovered by subscribing will be sent. In this way, **we have eliminated the optional ones in the repository response.**

If you are interested in knowing more about the data layer with MoyaRx and Codable or mobile app development in general, I highly recommend you to subscribe to our monthly newsletter by clicking [here](http://eepurl.com/cC96MY). 

 

## If you found this article about the data layer with MoyaRx and Codable interesting, you might like…

 

[iOS Objective-C app: sucessful case study](https://dev.to/apium_hub/protected-ios-objective-c-app-cornerjob-successfull-case-study-89e)

[Mobile app development trends of the year](https://dev.to/apium_hub/mobile-app-development-trends-of-the-year)

[Banco Falabella wearable case study ](https://apiumhub.com/tech-blog-barcelona/banco-falabella-wearable-ios-android/)

[Mobile development projects](https://apiumhub.com/software-projects-barcelona/) 

[Viper architecture advantages for iOS apps](https://apiumhub.com/tech-blog-barcelona/viper-architecture/) 

[Why Kotlin ? ](https://dev.to/apium_hub/why-kotlin-language-android-why-did-google-choose-kotlin--639)

[Software architecture meetups](https://dev.to/apium_hub/apiumhub-software-architecture-meetups-in-barcelona-31df)

 

The post [How to simplify the data layer with MoyaRx and Codable](https://apiumhub.com/tech-blog-barcelona/data-layer-with-moyarx-and-codable/) appeared first on [Apiumhub](https://apiumhub.com).