RxSwiftの道01-----シンプルなRxSwiftで使用

8673 ワード

1年以上swiftを使ってやっと穴に入るRxSwiftとOC時代のReactiveCocoaにはあまり差がありませんが、ここではまず簡単な使い方を挙げて、コードの書き方を減らすことができます.構造がはっきりしています.RxSwiftを使わないとき、buttonのイベントを書くときはそうです.
 override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: 40, y: 100, width: 70, height: 30))
        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: 40, y: 100, width: 70, height: 30))
        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を用いることで一部のコードを簡略化し,コード構造をより明確にすることができ,その他は後述する