Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RxSwift で作る UITableView

Takeo CHIBA
September 23, 2017

RxSwift で作る UITableView

RxSwift 初心者が RxSwift を使って、UITableView を構築してみました。
発表後にアドバイスをいただき、大きなデータを扱う UITableView には RxSwift は向かないという結論になりました。

サンプルはこちら。Xcode8.3.3 です。
https://github.com/taketomato/rxTableViewSample

Takeo CHIBA

September 23, 2017
Tweet

More Decks by Takeo CHIBA

Other Decks in Programming

Transcript

  1. What is RxSwfit ? • ReactiveX (Reactive Extensions) ͷ Swift

    ࣮૷ • ϦΞΫςΟϒϓϩάϥϛϯάΛ࣮ݱ͢Δͨ ΊͷσβΠϯͱɺͦͷ࣮૷ϥΠϒϥϦ • RxJAVA ΍ RxJS ͳͲ֤ݴޠ/ϓϥοτϑΥʔ Ϝ༻ͷ࣮૷͕͋Δ
  2. RxSwift Λ࢖ͬͯ Let’s ࣮૷ ΍Δ͜ͱ 1. ഑ྻσʔλΛ UITableView ʹදࣔͰ͖ΔΑ͏ʹ͢Δ 2.

    Realm ͷσʔλΛ UITableView ʹදࣔͰ͖ΔΑ͏ʹ͢Δ 3. Realm ͷσʔλΛηΫγϣϯදࣔͰ͖ΔΑ͏ʹ͢Δ * Realm…ϞόΠϧ޲͚σʔλϕʔε
  3. ࣄલ४උ • RxSwift / RxRealm / RxDataSources ͷಋೖ͕ඞཁ • CocoaPods

    / Carthage ͰಋೖͰ͖·͢ github "ReactiveX/RxSwift" ~> 3.0 github “RxSwiftCommunity/RxRealm" github "RxSwiftCommunity/RxDataSources" ~> 1.0 <Carthage ͷ৔߹> Cartfile ίϚϯυ $ carthage update
  4. 1. ഑ྻσʔλΛ UITableView ʹදࣔͰ͖Δ Α͏ʹ͢Δ arrayObservable .bind(to: tableView.rx.items(cellIdentifier: “Cell")) {

    row, element, cell in // セルの設定 } .addDisposableTo(disposeBag) Observable Observer
  5. 1. ഑ྻσʔλΛ UITableView ʹදࣔͰ͖Δ Α͏ʹ͢Δ arrayObservable .bind(to: tableView.rx.items) { tableView,

    row, element in // セルの設定 } .addDisposableTo(disposeBag) arrayObservable .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag)
  6. 2. Realm ͷ σʔλΛ UITableView ʹද ࣔͰ͖ΔΑ͏ʹ͢Δ Observable.changeset(from: realmResult) .subscribe(onNext:

    { [weak self] results, changes in // tableView の更新 }) .addDisposableTo(disposeBag) • RxRealm Ͱ༻ҙ͞Ε͍ͯΔϝιουΛ࢖͏͜ͱͰɺRealm ͷมߋΛ؂ࢹ͢Δ͜ͱ͕Ͱ͖·͢
  7. 2. Realm ͷ σʔλΛ UITableView ʹද ࣔͰ͖ΔΑ͏ʹ͢Δ Observable.changeset(from: realmResult) .subscribe(onNext:

    { [weak self] results, changes in // tableView の更新 }) .addDisposableTo(disposeBag) • RxRealm Ͱ༻ҙ͞Ε͍ͯΔϝιουΛ࢖͏͜ͱͰɺRealm ͷมߋΛ؂ࢹ͢Δ͜ͱ͕Ͱ͖·͢ Observable Observer
  8. 3. Realm ͷσʔλΛηΫγϣϯදࣔͰ ͖ΔΑ͏ʹ͢Δ • ઐ༻ͷ datasource Λ༻ҙ͢Δ • Realm

    σʔλΛखಈͰηΫγϣϯ෼ྨ͢Δ (=SectionModel) • SectionModel ͷ Observable Λ bind ͢Δ
  9. 3. Realm ͷσʔλΛηΫγϣϯදࣔͰ ͖ΔΑ͏ʹ͢Δ let dataSource = RxTableViewSectionedReloadDataSource <SectionModel<String, String>>()

    sectionModelObservable .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag)
  10. 3. Realm ͷσʔλΛηΫγϣϯදࣔͰ ͖ΔΑ͏ʹ͢Δ let dataSource = RxTableViewSectionedReloadDataSource <SectionModel<String, String>>()

    sectionModelObservable .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) datasource sectionModel ͷ Observable
  11. 3. Realm ͷσʔλΛηΫγϣϯදࣔͰ ͖ΔΑ͏ʹ͢Δ let dataSource = RxTableViewSectionedReloadDataSource <SectionModel<String, String>>()

    sectionModelObservable .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) ·ͩࣗಈߋ৽Ͱ͖͍ͯ·ͤΜ (; _ ;)