๐Ÿงš RxSwift + Moya + HandyJSON + Plugins.

Overview

RxNetworks

Carthage compatible Releases Compatible CocoaPods Compatible Platform

๐Ÿงš . RxSwift + Moya + HandyJSON + Plugins. ๐Ÿ‘’ ๐Ÿ‘’ ๐Ÿ‘’


English | ็ฎ€ไฝ“ไธญๆ–‡

This is a set of infrastructure based on RxSwift + Moya

MoyaNetwork

This module is based on the Moya encapsulated network API architecture.

  • Mainly divided into 3 parts:
    • NetworkConfig: Set the configuration information at the beginning of the program.
      • baseURL: Root path address to base URL.
      • baseParameters: Default basic parameters, like: userID, token, etc.
      • baseMethod: Default request method type.
      • updateBaseParametersWithValue: Update default base parameter value.
    • RxMoyaProvider: Add responsiveness to network requests, returning Single sequence.
    • NetworkUtil: Network related functions
      • defaultPlugin: Add default plugin.
      • transformAPISingleJSON: Transforms a Single sequence object.
      • handyConfigurationPlugin: Handles configuration plugins.
    • PluginSubType: Inherit and replace the Moya plug-in protocol to facilitate subsequent expansion.
      • configuration: After setting the network configuration information, before starting to prepare the request, this method can be used in scenarios such as key invalidation, re-acquiring the key and then automatically re-requesting the network.
      • lastNever: When the last network response is returned, this method can be used in scenarios such as key failure to re-obtain the key and then automatically re-request the network.
    • NetworkAPI: Add protocol attributes and encapsulate basic network requests based on TargetType.
      • ip: Root path address to base URL.
      • parameters: Request parameters.
      • plugins: Set network plugins.
      • stubBehavior: Whether to take the test data.
      • request: Network request method and return a Single sequence object.
    • NetworkAPIOO: OOP converter, MVP to OOP, convenient for friends who are used to OC thinking
      • cdy_ip: Root path address to base URL.
      • cdy_path: Request path.
      • cdy_parameters: Request parameters.
      • cdy_plugins: Set network plugins.
      • cdy_testJSON: Network testing json string.
      • cdy_testTime: Network test data return time, the default is half a second.
      • cdy_HTTPRequest: Network request method and return a Single sequence object.
    • NetworkX: extension function methods etc.
      • toJSON: to JSON string.
      • toDictionary: JSON string to dictionary.
      • +=: Dictionary concatenation.

๐ŸŽท - OO Example 1:

class OOViewModel: NSObject {
    
    let disposeBag = DisposeBag()
    
    let data = PublishRelay
   
    ()
    
    func loadData() {
        var api = NetworkAPIOO.init()
        api.cdy_ip = NetworkConfig.baseURL
        api.cdy_path = "/ip"
        api.cdy_method = .get
        api.cdy_plugins = [NetworkLoadingPlugin.init()]
        
        api.cdy_HTTPRequest()
            .asObservable()
            .compactMap{ (($0 as! NSDictionary)["origin"] as? String) }
            .bind(to: data)
            .disposed(by: disposeBag)
    }
}

   

๐ŸŽท - MVP Example 2:

() /// Configure the loading animation plugin let APIProvider: MoyaProvider = { let configuration = URLSessionConfiguration.default configuration.headers = .default configuration.timeoutIntervalForRequest = 30 let session = Moya.Session(configuration: configuration, startRequestsImmediately: false) let loading = NetworkLoadingPlugin.init() return MoyaProvider (session: session, plugins: [loading]) }() func loadData() { APIProvider.rx.request(api: LoadingAPI.test2("666")) .asObservable() .subscribe { [weak self] (event) in if let dict = event.element as? NSDictionary { self?.data.accept(dict) } }.disposed(by: disposeBag) } }">
enum LoadingAPI {
    case test2(String)
}

extension LoadingAPI: NetworkAPI {
    
    var ip: APIHost {
        return NetworkConfig.baseURL
    }
    
    var path: String {
        return "/post"
    }
    
    var parameters: APIParameters? {
        switch self {
        case .test2(let string): return ["key": string]
        }
    }
}


class LoadingViewModel: NSObject {
    
    let disposeBag = DisposeBag()
    
    let data = PublishRelay
     
      ()
    
    /// Configure the loading animation plugin
    let APIProvider: MoyaProvider
      
        = {
        let configuration = URLSessionConfiguration.default
        configuration.headers = .default
        configuration.timeoutIntervalForRequest = 30
        let session = Moya.Session(configuration: configuration, startRequestsImmediately: false)
        let loading = NetworkLoadingPlugin.init()
        return MoyaProvider
       
        (session: session, plugins: [loading])
    }()
    
    func loadData() {
        APIProvider.rx.request(api: LoadingAPI.test2("666"))
            .asObservable()
            .subscribe { [weak self] (event) in
                if let dict = event.element as? NSDictionary {
                    self?.data.accept(dict)
                }
            }.disposed(by: disposeBag)
    }
}

       
      
     

๐ŸŽท - MVVM Example 3:

class CacheViewModel: NSObject {

    let disposeBag = DisposeBag()
    
    struct Input {
        let count: Int
    }

    struct Output {
        let items: Driver<[CacheModel]>
    }
    
    func transform(input: Input) -> Output {
        let elements = BehaviorRelay<[CacheModel]>(value: [])
        
        let output = Output(items: elements.asDriver())
        
        request(input.count)
            .asObservable()
            .bind(to: elements)
            .disposed(by: disposeBag)
        
        return output
    }
}

extension CacheViewModel {
    
    func request(_ count: Int) -> Driver<[CacheModel]> {
        CacheAPI.cache(count).request()
            .asObservable()
            .mapHandyJSON(HandyDataModel<[CacheModel]>.self)
            .compactMap { $0.data }
            .observe(on: MainScheduler.instance)
            .delay(.seconds(1), scheduler: MainScheduler.instance) 
            .asDriver(onErrorJustReturn: [])
    }
}

๐ŸŽท - Chain Example 4:

Observable { return ChainAPI.test.request() .asObservable() .map { ($0 as! NSDictionary)["origin"] as! String } .catchAndReturn("") // Exception thrown } func requestData(_ ip: String) -> Observable { return ChainAPI.test2(ip).request() .asObservable() .map { ($0 as! NSDictionary) } .catchAndReturn(["data": "nil"]) } }">
class ChainViewModel: NSObject {
    
    let disposeBag = DisposeBag()
    
    let data = PublishRelay
     
      ()
    
    func chainLoad() {
        requestIP()
            .flatMapLatest(requestData)
            .subscribe(onNext: { [weak self] data in
                self?.data.accept(data)
            }, onError: {
                print("Network Failed: \($0)")
            }).disposed(by: disposeBag)
    }
    
}

extension ChainViewModel {
    
    func requestIP() -> Observable
      
        {
        return ChainAPI.test.request()
            .asObservable()
            .map { ($0 as! NSDictionary)["origin"] as! String }
            .catchAndReturn("") // Exception thrown
    }
    
    func requestData(_ ip: String) -> Observable
       
         {
        return ChainAPI.test2(ip).request()
            .asObservable()
            .map { ($0 as! NSDictionary) }
            .catchAndReturn(["data": "nil"])
    }
}

       
      
     

๐ŸŽท - Batch Example 5:

, let data2 = $1 as? Dictionary , let data3 = $2 as? Dictionary else { return } data1 += data2 data1 += data3 self?.data.accept(data1) }, onFailure: { print("Network Failed: \($0)") }).disposed(by: disposeBag) } }">
class BatchViewModel: NSObject {
    
    let disposeBag = DisposeBag()
    
    let data = PublishRelay
     
      ()
    
    /// Configure loading animation plugin
    let APIProvider: MoyaProvider
      
        = {
        let configuration = URLSessionConfiguration.default
        configuration.headers = .default
        configuration.timeoutIntervalForRequest = 30
        let session = Moya.Session(configuration: configuration, startRequestsImmediately: false)
        let loading = NetworkLoadingPlugin.init()
        return MoyaProvider
       
        (session: session, plugins: [loading])
    }()
    
    func batchLoad() {
        Single.zip(
            APIProvider.rx.request(api: BatchAPI.test),
            APIProvider.rx.request(api: BatchAPI.test2("666")),
            APIProvider.rx.request(api: BatchAPI.test3)
        ).subscribe(onSuccess: { [weak self] in
            guard var data1 = $0 as? Dictionary
        
         ,
                  let data2 = $1 as? Dictionary
         
          , let data3 = $2 as? Dictionary
          
            else { return } data1 += data2 data1 += data3 self?.data.accept(data1) }, onFailure: { print("Network Failed: \($0)") }).disposed(by: disposeBag) } } 
          
         
        
       
      
     

MoyaPlugins

This module is mainly based on moya package network related plug-ins

  • At present, 4 plug-ins have been packaged for you to use:

๐Ÿ  - Simple to use, implement the protocol method in the API protocol, and then add the plugin to it:

var plugins: APIPlugins {
    let cache = NetworkCachePlugin(cacheType: .networkElseCache)
    let loading = NetworkLoadingPlugin.init(delayHideHUD: 0.5)
    return [loading, cache]
}

HandyJSON

This module is based on HandyJSON package network data parsing

  • Roughly divided into the following 3 parts:
    • HandyDataModel: Network outer data model
    • HandyJSONError: Parse error related
    • RxHandyJSON: HandyJSON data parsing, currently provides two parsing solutions
      • Option 1: Combine HandyDataModel model to parse out data.
      • Option 2: Parse the data of the specified key according to keyPath, the precondition is that the json data source must be in the form of a dictionary.

๐ŸŽท - Example of use in conjunction with the network part:

func request(_ count: Int) -> Driver<[CacheModel]> {
    CacheAPI.cache(count).request()
        .asObservable()
        .mapHandyJSON(HandyDataModel<[CacheModel]>.self)
        .compactMap { $0.data }
        .observe(on: MainScheduler.instance)
        .delay(.seconds(1), scheduler: MainScheduler.instance)
        .asDriver(onErrorJustReturn: [])
}

CocoaPods Install

Ex: Import Network Architecture API
- pod 'RxNetworks/MoyaNetwork'

Ex: Import Model Anslysis 
- pod 'RxNetworks/HandyJSON'

Ex: Import loading animation plugin
- pod 'RxNetworks/MoyaPlugins/Loading'

Remarks

The general process is almost like this, the Demo is also written in great detail, you can check it out for yourself. ๐ŸŽท

RxNetworksDemo

Tip: If you find it helpful, please help me with a star. If you have any questions or needs, you can also issue.

Thanks. ๐ŸŽ‡

About the author


License

RxNetworks is available under the MIT license. See the LICENSE file for more info.


You might also like...
Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

GitTime is GitHub Tracking App. Using ReactorKit, RxSwift, Moya.
GitTime is GitHub Tracking App. Using ReactorKit, RxSwift, Moya.

GitTime Feature Activity: GitHub Contributions graph & Event lists Trending: Trending Repositories & Developers Buddys: Show your buddy's contribution

HandyJSON is a framework written in Swift which to make converting model objects to and from JSON easy on iOS.

HandyJSON To deal with crash on iOS 14 beta4 please try version 5.0.3-beta HandyJSON is a framework written in Swift which to make converting model ob

Realm RxSwift - This application was written in order to use Realm, RxSwift frameworks in real example

Realm_RxSwift This simple app was written to introduce basic operations of some

This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

The template for Delta Client plugins.

Delta Plugin Template This repository is a template for Delta Client plugins. To create a plugin, create a repo from this template repo and then repla

A repository of example plugins for Delta Client

Example Plugins for Delta Client This repository contains a few example plugins to help developers get a practical understanding of how to use the plu

A library for creating Stream Deck plugins in Swift.

StreamDeck A library for creating Stream Deck plugins in Swift. Usage Your plugin class should inherit from StreamDeckPlugin, which handles the WebSoc

Validation plugin for Moya.Result

MoyaResultValidate Why? Sometimes we need to verify that the data returned by the server is reasonable, when Moya returns Result.success. JSON returne

๐Ÿฏ Syntactic sugar for Moya

MoyaSugar Syntactic sugar for Moya. Why? Moya is an elegant network abstraction layer which abstracts API endpoints gracefully with enum. However, it

XTextHandler - Xcode Source Editor Extension Tools (Xcode 8 Plugins)
XTextHandler - Xcode Source Editor Extension Tools (Xcode 8 Plugins)

Download Let's Swift! xTextHandler has been rewritten in Swift. The Objective-C version can be found in: https://github.com/cyanzhong/xTextHandler-obj

SwiftHooks is a little module for plugins, in Swift
SwiftHooks is a little module for plugins, in Swift

A Hook represents a "pluggable" point in a software model. They provide a mechanism for "tapping" into such points to get updates, or apply additional functionality to some typed object.

A collection of Swift Package Manager plugins.

KipplePlugins A collection of Swift Package Manager plugins. โš ๏ธ The code in this library has been made public as-is for the purposes of education, dis

Example of Clean Architecture of iOS app using RxSwift
Example of Clean Architecture of iOS app using RxSwift

Clean architecture with RxSwift Contributions are welcome and highly appreciated!! You can do this by: opening an issue to discuss the current solutio

Spin aims to provide a versatile Feedback Loop implementation working with the three main reactive frameworks available in the Swift community (RxSwift, ReactiveSwift and Combine)
Spin aims to provide a versatile Feedback Loop implementation working with the three main reactive frameworks available in the Swift community (RxSwift, ReactiveSwift and Combine)

With the introduction of Combine and SwiftUI, we will face some transition periods in our code base. Our applications will use both Combine and a thir

ModernRIBs is recreated by removing additional dependencies such as RxSwift from Uber's RIBs.
ModernRIBs is recreated by removing additional dependencies such as RxSwift from Uber's RIBs.

ModernRIBs is recreated by removing additional dependencies such as RxSwift from Uber's RIBs. Only Combine was used. All features provided by RIBs can

iOS & OSX Bluetooth library for RxSwift
iOS & OSX Bluetooth library for RxSwift

RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant. It's backed by RxSwift and CoreBluetooth and it prov

A testable RxSwift wrapper around MultipeerConnectivity

A testable RxSwift wrapper around MultipeerConnectivity

Comments
  • MVVM็š„ไฝฟ็”จๅฆ‚ๆžœ่Žทๅ–่ฏทๆฑ‚ๅคฑ่ดฅ

    MVVM็š„ไฝฟ็”จๅฆ‚ๆžœ่Žทๅ–่ฏทๆฑ‚ๅคฑ่ดฅ

    ๆฏ”ๅฆ‚็Žฐๅœจๆˆ‘HomeAPI.recommend("1004587") .request() .mapHandyJSON(HandyDataModel<[HomeRoomInfoModel]>.self) .compactMap({$0.data}).observe(on: MainScheduler.instance) .catchAndReturn([]) ๆฏ”ๅฆ‚ๆˆ‘็š„View ไธญๆœ‰ไธ‹ๆ‹‰ๅˆทๆ–ฐ ๆˆ‘ๅœจ่ฏทๆฑ‚ๆŽฅๅฃ็š„ๆ—ถๅ€™ ๅฆ‚ๆžœ่ฏทๆฑ‚ๅคฑ่ดฅไบ† ๆˆ‘่ฆ้€š็ŸฅๅˆฐviewไธญๅœๆญขheaderView็š„ๅˆทๆ–ฐ ่ฟ™็งๆƒ…ๅ†ต่ฆๆ€Žไนˆๆž

    opened by fengshuo1992 1
Releases(0.1.0)
Owner
77ใ€‚
๐Ÿ˜Ž๐Ÿ˜Ž้…ท็ˆฑๆ‘‡ๆปšไน็š„้ผ“ๆ‰‹๏ผŒๆœ‰ๆ—ถไนŸ่ฆๅฐๆธ…ๆ–ฐใ€‚
77ใ€‚
This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

Angel Rada 19 Sep 8, 2022
A testable RxSwift wrapper around MultipeerConnectivity

A testable RxSwift wrapper around MultipeerConnectivity

RxSwift Community 69 Jul 5, 2022
Simple REST Client based on RxSwift and Alamofire.

RxRestClient Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 10.0+ tvOS 10.

STDev 16 Nov 19, 2022
Write clean, concise and declarative network code relying on URLSession, with the power of RxSwift. Inspired by Retrofit.

ReactiveAPI Reactive API library allows you to write clean, concise and declarative network code, with the power of RxSwift and URLSession! iOS Demo A

Sky UK Ltd 79 Nov 19, 2022
RxSwift+MVVM 4์‹œ๊ฐ„์— ๋๋‚ด๊ธฐ

RxSwift+MVVM 4์‹œ๊ฐ„์— ๋๋‚ด๊ธฐ RxSwift 4์‹œ๊ฐ„์— ๋๋‚ด๊ธฐ (์‹œ์ฆŒ2) Preface ์š”์ฆ˜ ๊ด€์‹ฌ์ด ๋†’์€ RxSwift! RxSwift๋Š”

์ฝ”์ฝ”์ข… 0 Jan 9, 2022
iOS Todo Application using RxSwift and ReactorKit

RxTodo RxTodo is an iOS application developed using ReactorKit. This project is for whom having trouble with learning how to build a RxSwift applicati

Suyeol Jeon 1.3k Jan 3, 2023
Permission Util for iOS (feat.RxSwift)

EzRxPermission Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation EzR

Yunjae-Na 4 Jun 30, 2022
GitHub iOS client in RxSwift and MVVM-C clean architecture

GitHub iOS client in RxSwift and MVVM-C clean architecture. FlutterHub - Flutter version available at an early stage KotlinHub - Android version is co

Khoren Markosyan 2.7k Jan 7, 2023
Simple REST Client based on RxSwift and Alamofire.

RxRestClient Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 10.0+ tvOS 10.

STDev 16 Nov 19, 2022
Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

Edwin Vermeer 964 Dec 14, 2022