Skip to content

RxSwift + Moya + Cache Network request cache encapsulation

License

Notifications You must be signed in to change notification settings

ChoshimWy/NetworkManager

Repository files navigation

NetworkManager-Moya 0.1.2

CI Status Version License Platform

Example

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

Requirements

  • iOS 10.0
  • Swift 5.0
  • Xcode 11

Installation

NetworkManager-Moya is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'NetworkManager-Moya', '~> 0.1.2'

# or
pod 'NetworkManager-Moya/Cache', '~> 0.1.2'

Usage

Do not use cache

NetworkManager.default.provider
    .rx
    .request(MultiTarget(Api.category))
    .asObservable().distinctUntilChanged()
    .map(BaseModel<ListData>.self)
    .map {$0.data.list}
    .subscribe(onNext: { (list) in
        self.items = list
        self.tableView.reloadData()
    }, onError: { (e) in
        print(e.localizedDescription)
    }).disposed(by: dispose)

Or you can use TargetType to request directly

Api.category.request()
    .map(BaseModel<ListData>.self)
    .map { $0.data.list }
    .subscribe(onSuccess: { (list) in
        self.items = list
        self.tableView.reloadData()
    }) { (e) in
        print(e.localizedDescription)
}.disposed(by: dispose)

Use cache

NetworkManager.default.provider
    .rx
    .onCache(MultiTarget(Api.category))
    .distinctUntilChanged()
    .map(BaseModel<ListData>.self)
    .map {$0.data.list}
    .subscribe(onNext: { (list) in
        self.items = list
        self.tableView.reloadData()
    }, onError: { (e) in
        print(e.localizedDescription)
    }).disposed(by: dispose)
    
/// or

Api.category.cache()
    .distinctUntilChanged()
    .map(BaseModel<ListData>.self)
    .map { $0.data.list }
    .subscribe(onNext: { (model) in
        print(model.first?.name ?? "")
        self.items = model
        self.tableView.reloadData()
    }, onError: { (e) in
        print(e.localizedDescription)
    }).disposed(by: dispose)

You can also customize the use of the plugin

let configuration = Configuration()
configuration.plugins.append(LoggingPlugin())
let manager = NetworkManager(configuration: configuration)
manager.provider
    .rx
    .request(MultiTarget(Api.category))
    .asObservable().distinctUntilChanged()
    .map(BaseModel<ListData>.self)
    .map {$0.data.list}
    .subscribe(onNext: { (list) in
        self.items = list
        self.tableView.reloadData()
    }, onError: { (e) in
        print(e.localizedDescription)
    }).disposed(by: dispose)

Author

WeiRuJian, [email protected]

License

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

About

RxSwift + Moya + Cache Network request cache encapsulation

Resources

License

Stars

Watchers

Forks

Packages

No packages published