天天看点

RxSwift之路01-----简单的RxSwift使用

使用一年多swift后终于要入坑RxSwift了和在OC时代的ReactiveCocoa没有多少差别,这里先举一些简单的使用,可以减少代码的书写,结构清晰

在不使用RxSwift时,我们写button的事件时是这样的

override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: , y: , width: , height: ))
        button.backgroundColor = UIColor.red
        button.addTarget(self, action: #selector(buttonAction), for: UIControlEvents.touchUpInside)
        view.addSubview(button)
        }

  @objc func buttonAction(){
       print("点击事件")
    }
           

使用RxSwift后代码如下

let button = UIButton(frame: CGRect(x: , y: , width: , height: ))
        button.backgroundColor = UIColor.red
        view.addSubview(button)
        button.rx.tap
        .subscribe(onNext: {
          print("Button Tap")
        })
        .disposed(by: disposeBag)
           

从上面可以看出,控件的创建和事件的添加可以放在一起,是代码更加清晰明了

2.举例2

创建一个UIScrollerView并实现它的代理事件,通常的写法是创建一个extension单独的管理代理方法的事件,种方法可以清晰的单独的带扩展中处理代理方法,看着非常的整洁,但是使用RxSwift后发现可以更简单的处理这些事务逻辑

如下:

class ViewController: UIViewController {
 override func viewDidLoad() {
        super.viewDidLoad()
let scrollerView = UIScrollView(frame: CGRect(x: 10, y: 200, width: 200, height: 100))
        scrollerView.contentSize = CGSize(width: 200, height: 10000)
        scrollerView.backgroundColor = UIColor.orange
        scrollerView.delegate = self
        view.addSubview(scrollerView)
    }
 }
extension ViewController:UIScrollViewDelegate{
       func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset.y)
    }
}
           

上面的代码在滚动的时候就可以监听到Y值

在使用RxSwift后就更简单了

class ViewController: UIViewController {
    let disposeBag = DisposeBag()
 override func viewDidLoad() {
        super.viewDidLoad()
let scrollerView = UIScrollView(frame: CGRect(x: 10, y: 200, width: 200, height: 100))
        scrollerView.contentSize = CGSize(width: 200, height: 10000)
        scrollerView.backgroundColor = UIColor.orange
        view.addSubview(scrollerView)
scrollerView.rx.contentOffset
            .subscribe(onNext: { (content) in
               print(content.y)
            })
        .disposed(by: disposeBag)
    }
 }
           

举例3

使用系统自带的网络请求的方法

URLSession.shared.dataTask(with: URLRequest(url: url)) {
    (data, response, error) in
    guard error == nil else {
        print("Data Task Error: \(error!)")
        return
    }

    guard let data = data else {
        print("Data Task Error: unknown")
        return
    }

    print("Data Task Success with count: \(data.count)")
}.resume()
           

在使用RxSwift演示的代码的如下

let url = URL(fileURLWithPath: "https://www.baidu.com/")
URLSession.shared.rx.data(request: URLRequest(url: url))
    .subscribe(onNext: { data in
        print("Data Task Success with count: \(data.count)")
    }, onError: { error in
        print("Data Task Error: \(error)")
    })
    .disposed(by: disposeBag)
           

举例4.通知

override func viewDidLoad() {
    super.viewDidLoad()

    ntfObserver = NotificationCenter.default.addObserver(
          forName: .UIApplicationWillEnterForeground,
          object: nil, queue: nil) { (notification) in
        print("Application Will Enter Foreground")
    }
}

deinit {
    NotificationCenter.default.removeObserver(ntfObserver)
}
           

使用RxSwift演示演示代码如下

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.rx
        .notification(.UIApplicationWillEnterForeground)
        .subscribe(onNext: { (notification) in
            print("Application Will Enter Foreground")
        })
        .disposed(by: disposeBag)
}
           

从以上简单的例子可以看出,使用RxSwift可以简化部分代码,使代码结构更清晰,其他的后面在讨论