SwiftRex Middlewares
一组实用且可复用的中间件,可以帮助您快速启动应用。
Logger Middleware
将此中间件添加入链,将对所有事件和操作进行记录,包括状态在 reducers 之前和之后的信息,以及每次操作所消耗的时间。建议将其作为链中的第一个中间件,以确保时间记录更准确。
安装
RxSwift 用户
pod 'RxSwift'
pod 'SwiftRex/UsingRxSwift'
pod 'SwiftRex-LoggerMiddleware/UsingRxSwift'
ReactiveSwift 用户
pod 'ReactiveSwift'
pod 'SwiftRex/UsingReactiveSwift'
pod 'SwiftRex-LoggerMiddleware/UsingReactiveSwift'
使用
import Foundation
import SwiftRex
import SwiftRex_LoggerMiddleware
public let mainReducer: () -> Reducer<MainState> = {
// ....
}
public let mainMiddleware: () -> ComposedMiddleware<MainState> = {
LoggerMiddleware()
// <> RouterMiddleware().lift(\.navigation)
// <> DirectLineMiddleware()
// <> ReachabilityMiddleware().lift(\.networkState)
// <> ...
}
extension MainStore {
public convenience init() {
self.init(initialState: .init(),
reducer: mainReducer(),
middleware: mainMiddleware())
}
}
Reachability Middleware
将此中间件插入您的链中,以监控网络可达性。
安装
RxSwift 用户
pod 'RxSwift'
pod 'SwiftRex/UsingRxSwift'
pod 'SwiftRex-ReachabilityMiddleware/UsingRxSwift'
ReactiveSwift 用户
pod 'ReactiveSwift'
pod 'SwiftRex/UsingReactiveSwift'
pod 'SwiftRex-ReachabilityMiddleware/UsingReactiveSwift'
使用方法
import Foundation
import Reachability
import SwiftRex
import SwiftRex_ReachabilityMiddleware
public struct MainState: Equatable, Codable {
// 1 - Add the property to hold reachability state anywhere on your main state tree
public var networkState: Reachability.Connection = .none
// ... public var ...
public init() { }
}
public let mainReducer: () -> Reducer<MainState> = {
// 2 - Add reachability reducer in any position of your reducer chain
// Please notice that we lift the reducer for the property of type Reachability.Connection
// to a reducer of type MainState by providing the KeyPath to the property.
Reducer.reachability.lift(\.networkState)
// <> ...
}
public let mainMiddleware: () -> ComposedMiddleware<MainState> = {
// 3 - Add reachability middleware in any position of your middleware chain
// Please notice that we lift the middleware for the property of type Reachability.Connection
// to a middleware of type MainState by providing the KeyPath to the property.
ReachabilityMiddleware().lift(\.networkState)
// <> ...
}
extension MainStore {
public convenience init() {
self.init(initialState: .init(),
reducer: mainReducer(),
middleware: mainMiddleware())
}
}
final class MyViewController: UIViewController {
private let stateProvider = Environment.current.stateProvider()
override func viewDidLoad() {
super.viewDidLoad()
setupBindings()
}
private func setupBindings() {
// 4 - You can now observe that property
stateProvider
.map { $0.networkState }
.distinctUntilChanged()
.asDriver(onErrorJustReturn: .none)
.drive(onNext: { connection in
switch connection {
case .none:
showNoConnectionRibbon()
case .wifi, .cellular:
hideNoConnectionRibbon()
}
}).disposed(by: disposeBag)
}
private func showNoConnectionRibbon() {
// TODO: Implement
}
private func hideNoConnectionRibbon() {
// TODO: Implement
}
}