首页 > 其他分享 >ReactorKit的使用(单向数据流架构) swift

ReactorKit的使用(单向数据流架构) swift

时间:2022-10-25 17:48:22浏览次数:49  
标签:reactor self State state ReactorKit result 数据流 swift

Reactor的最大的作用就是将业务逻辑从View中抽离出来,可以让我们代码分工变的更加清晰明朗,多人开发时也便于后期的管理和维护。

ReactorKit是一个面向响应式单向 Swift 应用程序架构的框架。在 ReactorKit 框架中,用户动作和视图状态都是通过可观测的流传递给每一层。这些流是单向的,因此,视图只能发出动作,而响应者只能发出状态,如下图所示:

 

 

如果 ViewController 是纯代码开发的:则其遵守 View 协议。

class LoginView: BaseScrollBgController, View {
    
    var disposeBag = DisposeBag()

}

 

当 reactor 属性被设置时,bind(reactor:) 方法就会被调用

 

extension LoginView {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.reactor = LoginReactor()
    }

}

 

extension LoginView {
    func bind(reactor: LoginReactor) {
        //view --- action --- reactor
        loginBtn.rx.tap
            .map { Reactor.Action.login }
            .bind(to: reactor.action)
            .disposed(by: disposeBag)
        //reactor --- state --- view
        reactor.state
            .flatMap { $0.loginResult }
            .subscribe(onNext: { [weak self] result in
                self?.loginTipLabel.text = result.message
                UIView.animate(withDuration: 3.0) {
                } completion: { _ in
                    if result.isSuccess {
                        UserDefaults.standard.setValue(true, forKey: YLConstant.kIsLogin)
                        DispatchQueue.main.async {
                            UIApplication.shared.keyWindow?.rootViewController = BaseTabBarController()
                        }
                    }
                }
            })
            .disposed(by: disposeBag)
    }
    
}

 

import ReactorKit
import RxRelay

class LoginReactor : Reactor {
    
    var initialState: State
    
    init() {
        initialState = State()
    }
    //页面状态
    struct State {
        let loginResult : PublishRelay<NetworkResult> = PublishRelay()
    }
    //用户行为
    enum Action {
        case login
    }
    //用户行为到页面状态的桥梁
    enum Mutation {
        case setLoginResult(NetworkResult)
    }
    //异步加载 由用户行为转为页面状态
    func mutate(action: Action) -> Observable<Mutation> {
        switch action {
        case .login:
            return service.passwordEncrypt(username: currentState.idCardNum, password: currentState.password)
                .flatMap { [unowned self] in service.login(username: self.currentState.idCardNum, password: $0) }
                .map(Mutation.setLoginResult)
        }
    }
    //旧状态 + 操作 == 新状态
    func reduce(state: State, mutation: Mutation) -> State {
        var state = state
        switch mutation {
        case let .setLoginResult(result):
            state.loginResult.accept(result)
        }
        return state
    }
    //moya登录网络请求类
    private let service = LoginService()
}

 

标签:reactor,self,State,state,ReactorKit,result,数据流,swift
From: https://www.cnblogs.com/huangzs/p/16825660.html

相关文章