An Elegant Networking Layer: Working with the Moya Framework

2020-02-14

While developing the "Waton App", a robust, easy-to-maintain networking layer was crucial. In February 2020, to build a more elegant networking layer, I chose the Moya framework and combined it deeply with RxSwift, putting together a clean, type-safe system for making network requests.

Why Moya?

On top of lower-level networking libraries such as Alamofire, Moya provides a higher level of abstraction. Its most distinctive feature is that all API requests are defined and managed through an enum. This approach brings several key advantages:

  • Type safety: Every API is a case of an enum, so the compiler helps us check API spellings and parameters, avoiding the low-level mistakes that can creep in when writing URLs and parameters by hand.
  • High cohesion: All the information related to an API (URL path, HTTP method, parameters, headers, task type, and so on) is aggregated into a single enum definition, making API management exceptionally clear and centralized.
  • Easy testing: Moya has powerful stubbing built in, making it effortless to return pre-set response data and to unit-test the networking layer.

Combining Moya with RxSwift

Moya's design and RxSwift are a match made in heaven. MoyaProvider can very naturally turn a network request into an Observable sequence. This lets us use RxSwift's chained syntax to carry the request through network call, data parsing, model mapping, and UI binding in one fluid pass, greatly improving the readability and expressiveness of the code.

provider.rx.request(.userProfile(id: 123))
    .map(User.self)
    .subscribe(onSuccess: { user in
        // Update UI with user
    }, onError: { error in
        // Handle error
    })
    .disposed(by: disposeBag)

Practical Takeaways

In the "Waton App", introducing Moya allowed me to build a highly structured, easily extensible networking layer. Whenever a new API is needed, I simply add a new case to the enum and provide its configuration — no other code needs to change at all. This high-cohesion, low-coupling design greatly improved the project's maintainability.

You could say that Moya is not the "terminator" of network requests but an excellent "organizer" of them. It taught me how to think about and design the networking layer of an iOS app in a more structured, more engineering-driven way.