RxSwift reintroduction

RxSwift reintroduction

0b26590a0a8b0f1da140ed5de9b68379?s=128

USAMI Kosuke

June 29, 2018
Tweet

Transcript

  1. RxSwift ࠶ೖ໳ USAMI Kosuke Fenrir Inc.

  2. RxSwift ͱ͸

  3. RxSwift ͱ͸ • ඇಉظͷΠϕϯτΛड͚औΔͨΊͷ࿮૊Έ • UI Πϕϯτड͚औΓ • Web API

    Ϩεϙϯεड͚औΓ • σʔλͷมԽͷ؂ࢹ
  4. ίʔυྫ : UIButton button.rx.tap .subscribe { [unowned self] _ in

    // Ϙλϯλοϓ࣌ͷॲཧ } .disposed(by: disposeBag)
  5. ίʔυྫ : UITextField textField.rx.text .subscribe { [unowned self] _ in

    // ςΩετೖྗ࣌ͷॲཧ } .disposed(by: disposeBag)
  6. ίʔυྫ : Notification NotificationCenter.default.rx.notification(..) .subscribe { [unowned self] _ in

    // ௨஌ड͚औΓ࣌ͷॲཧ } .disposed(by: disposeBag)
  7. ίʔυྫ : URLSession session.rx.response(request) .catchError { // Τϥʔ࣌ͷॲཧ .subscribe {

    // Ϩεϙϯεड͚औΓ࣌ͷॲཧ } .disposed(by: disposeBag)
  8. ΠϕϯτॲཧͷྲྀΕ • Observable ʹ Πϕϯτ͕ྲྀΕͯ͘Δ Sequence • rx.tap, rx.text, rx.notification,

    rx.response • Observable Λ subscribe ͢ΔͱΠϕϯτΛड͚औΕΔ • dispose ʹ subscription ͷഁغ
  9. ิ଍ɿObservable ʹྲྀΕͯ͘Δ΋ͷ • ྲྀΕͯ͘ΔΠϕϯτ͸ enum Ͱఆٛ͞Ε͍ͯΔ • .next : ஋

    • .error : Τϥʔऴྃ • .completed : ਖ਼ৗऴྃ
  10. σʔλόΠϯσΟϯά

  11. σʔλόΠϯσΟϯά • ྫ͑͹ɾɾɾ • Ϟσϧͷ஋ͷมԽΛ UI ʹ఻͍͑ͨ • UI ͷ஋ͷมԽΛϞσϧʹ఻͍͑ͨ

    • ͦͷͨΊͷखஈͱͯ͠ RxSwift ͕࢖͑Δ
  12. σʔλόΠϯσΟϯάͷͨΊͷखஈ • BehaviorRelay / PublishRelay • Observable ͷҰछ • .next

    ͚͕ͩྲྀΕΔɺऴྃ͠ͳ͍
  13. Relay ͷ࢖͍ํ : accept • accept Ͱ Relay ʹ .next

    ΠϕϯτΛૹΔ͜ͱ͕Ͱ͖Δ let relay = BehaviorRelay<String>(value: "000") relay.accept("111") relay.accept("222")
  14. Relay ͷ࢖͍ํ : bind • subscribe ͷ୅ΘΓʹ bind ͕࢖͑Δ relay

    .bind(to: label.rx.text) textField.rx.text .bind(to: relay)
  15. BehaviorRelay / PublishRelay • ྆ऀͷҧ͍ • ॳظ஋Λ࣋ͭ / ࣋ͨͳ͍ •

    value ϓϩύςΟͰݱࡏ஋͕औಘͰ͖Δ / Ͱ͖ͳ͍ • subscribe ͨ͠ͱ͖ݱࡏ஋͕ྲྀΕΔ / ྲྀΕͳ͍
  16. ViewModel struct ViewModel { let username = BehaviorRelay<String>(value: "") }

  17. Ϟσϧͷ஋ͷมԽΛ఻͑Δ class ViewController { override func viewDidLoad() { viewModel.username .bind(to:

    label.rx.text) .disposed(by: disposeBag) } }
  18. UI ͷ஋ͷมԽΛ఻͑Δ class ViewController { override func viewDidLoad() { textField.rx.text.orEmpty

    .bind(to: viewModel.username) .disposed(by: disposeBag) } }
  19. όΠϯσΟϯάͷ޲͖

  20. όΠϯσΟϯά͸୯ํ޲ • ʮόΠϯσΟϯάʯͱ͍͏ͱ૒ํ޲ͬΆ͍͚Ͳɾɾɾ • RxSwift ͷ৔߹͸୯ํ޲ • bind ͸࣮͸ subscribe

    Ͱ͋Δ͜ͱΛ஌Δͱ෼͔Γ΍͢ ͍
  21. ૒ํ޲όΠϯσΟϯά͸ผʹ͍Βͳ͍ • ૒ํ޲ͩͱσʔλͷྲྀΕͷ In / Out ͕۠ผͮ͠Β͍ • ΞϓϦઃܭͱͯ͠ɺσʔλͷྲྀΕΔํ޲ΛҙࣝͰ͖Δ͜ͱ͸େ ࣄ

  22. RxSwift Λ࢖͏͏͑Ͱ ͷཹҙ఺

  23. ͳΜͰ΋Ͱ͖͗͢Δ • ڧྗͳπʔϧͷͨΊແઅૢʹ࢖͏ͱ͜Μ͕Β͕Δ͜ͱ΋͋Δ • ΞϓϦઃܭΛߟ͓͑ͯ͘ • RxSwift ͕Կ͔ͷΞϓϦઃܭΛ༩͑ͯ͘ΕΔΘ͚Ͱ͸ͳ͍ • ΞϓϦઃܭʹରͯ͠ɺ࣮૷Λָʹ͢Δπʔϧ

  24. ϥΠϒϥϦࣗମͷن໛͕େ͖͍ • ༷ʑͳΫϥε͕͋ͬͯ೺Ѳͮ͠Β͍ • খ͞ͳ໰୊Λղܾ͍͚ͨͩ͠ͳΒಋೖΛͨΊΒ͏৔߹΋

  25. ্खʹ෇͖߹͑͹ศར • ࢖͍Ͳ͜ΖΛͪΌΜͱߟ͑ͯ࢖͑͹ɺͱͯ΋ศར • Enjoy RxSwift !