ReactiveCocoa 5.0 swift版本

转换的类型有:

RACSiganl 变为 Signal

  • 信号的第一种创建方式

     let producer = SignalProducer.init { (observe, disposable) in
    observe.send(value: "hello")
    }

      let subscriber = Observer(value: { print("输出 \($0)") })
    
      producer.start(subscriber)
    

  • 信号的第二种创建方式

    let (signalA, observerA) = Signal.pipe()
    signalA.observeValues { (value) in
    print("输出 (value)")
    }
    observerA.send(value: "signalA")

  • 两个信号都发送消息的时候才会调用

    let (signalA, observerA) = Signal.pipe()
    signalA.observeValues { (value) in
    print("输出 (value)")
    }
    observerA.send(value: "signalA")
    let (signalB, observerB) = Signal.pipe()
    Signal.combineLatest(signalA,signalB).observeValues { (value) in
    print( "收到的值(value.0) + (value.1)")
    }
    observerA.send(value: "我是信号1")
    observerA.sendCompleted()
    observerB.send(value: "我是信号2")
    observerB.sendCompleted()

  • 实现代理

    let redV = RedView()
    redV.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
    view.addSubview(redV)
    redV.signal.observeValues { (value) in
    print("接收到 (value)")
    }

RedView中代码

var btn : UIButton?
let (signal,obser) = Signal.pipe()

override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = UIColor.red
    btn = UIButton(type: .custom)
    btn?.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    btn?.setTitle("哈哈", for: .normal)
    addSubview(btn!)
    
    btn!.reactive.controlEvents(.touchUpInside).observeValues({ (_) in
        print("redView点击")
        self.obser.send(value: "redView代理")
        self.obser.sendCompleted()

    })

  • 其他

    //nameTf 跟 pwdTf同时有值得时候才会调用
    Signal.combineLatest(nameTf.reactive.continuousTextValues, pwdTf.reactive.continuousTextValues).observeValues { (name,pwd) in
    print("(name!) ++++ (pwd!)")
    }
    //button点击事件
    btn.reactive.controlEvents(.touchUpInside).observeValues { (_ button) in
    print(btn.tag)
    }
    //输入框字符大于6 按钮才可以点击 第一种写法
    Signal.combineLatest(nameTf.reactive.continuousTextValues,pwdTf.reactive.continuousTextValues).map { (name, password) -> Bool in
    return ((name?.characters.count)! >= 6 && (password?.characters.count)! >= 6)
    }.observeValues { (value) in
    btn.isEnabled = value
    }
    //输入框字符大于6 按钮才可以点击 第二种写法
    btn.reactive.isEnabled <~ Signal.combineLatest(nameTf.reactive.continuousTextValues,pwdTf.reactive.continuousTextValues).map { $0?.characters.count ?? 0 >= 6 && $1?.characters.count ?? 0 >= 6
    }
    //线程
    QueueScheduler.main.schedule(after: Date.init(timeIntervalSinceNow: 0.5)) {
    print("0.5秒后调用")
    }
    QueueScheduler.init().schedule(after: Date.init(timeIntervalSinceNow: 0.5)) {
    print("子线程调用")
    }
    //接收通知
    NotificationCenter.default.reactive.notifications(forName: Notification.Name(rawValue: "redView")).observeValues({ (noti) in
    print(noti.object ?? "通知")
    })

你可能感兴趣的:(ReactiveCocoa 5.0 swift版本)