RxSwift 实践使用

43 阅读1分钟

创建信号

class Person {
    var name = ""
    var age = 0
}

let password = MutableProperty<String>("") /// 系统类型
let modelProperty = MutableProperty<Person?>(nil)  /// 自定义类型

按钮点击

btn.reactive.controlEvents(.touchUpInside).observeValues { [weak self] _ in
   print("BtnClick")
}

监听 UITextField 输入

tf.reactive.continuousTextValues
            .observeValues { [weak self] text in
                label.text = text
                }

UITextField 防抖

let tf1 = UITextField(frame: CGRectMake(20, 100, 200, 44))
        tf1.backgroundColor = .yellow
        view.addSubview(tf1)
        
        tf1.reactive.continuousTextValues
            .debounce(0.3, on: QueueScheduler.main)
            .observeValues { [weak self] text in
                
            }

双向绑定(ViewModel 与 UITextField控件)

   viewModel.userName <~ tf1.reactive.continuousTextValues
   tf1.reactive.text <~ viewModel.userName.map { $0 }

信号合并

let isUserNameValid = tf1.reactive.continuousTextValues.map { !$0.isEmpty}
let isPasswordValid = tf2.reactive.continuousTextValues.map { !$0.isEmpty}
        
let isValid = Signal.combineLatest(isUserNameValid, isPasswordValid)
             .map{$0 && $1}
            .skipRepeats()  
   btn.reactive.isEnabled <~ isValid

监听自定义信号(订阅信号)

 let model = MutableProperty<Person?>(nil)
    var peronModel: Person? {
        didSet {
            if let _m = peronModel {
                model.value = _m
            }
        }
    }

model.signal
            .take(during: reactive.lifetime)
            .observe(on: UIScheduler())
            .observeValues { results in
                print("搜索结果: \(results)")
            }