Combine And SwiftUI

Combine And SwiftUI

Combine と SwiftUI

帰ってきた関西モバイルアプリ研究会#2 - connpass
https://kanmoba.connpass.com/event/134059/

Combine と SwiftUI について話しました #関モバ - usami-kの日記
https://usami-k.hatenablog.com/entry/2019/06/13/005041

0b26590a0a8b0f1da140ed5de9b68379?s=128

USAMI Kosuke

June 12, 2019
Tweet

Transcript

  1. 2.

    Combine • WWDC19 Ͱൃද͞Εͨ Reactive ϑϨʔϜϫʔΫ • υΩϡϝϯτʹ͸ "Reactive" ͱ͸ॻ͍ͯͳ͍͕

    • RxSwift ΍ ReactiveSwift ʹͱ͔ͬͯΘΔଘࡏ • ͨͩ͠ iOS 13 Ҏ߱Ͱ͔͠ಈ࡞͠ͳ͍
  2. 3.

    Combine ͷ༻ޠ • ֓೦͸ Rx (RxSwift) ʹ͍ۙɺ༻ޠ͸ҟͳΔ Combine RxSwift Publisher

    Observable Subscriber Observer CurrentValueSubject BehaviorSubject PassthroughSubject PublishSubject
  3. 4.

    Publisher protocol protocol Publisher { associatedtype Output associatedtype Failure: Error

    } • Τϥʔͷܕ͕໌ࣔతͳͷ͸ ReactiveSwift ͱಉ༷ͷར఺ • ྫ͑͹ Failure Λ Never ʹ͢Δ͜ͱͰɺΤϥʔग़ྗ͠ͳ͍ Publisher ͕ఆٛͰ͖ΔʢRxSwift ͸͜ͷ͋ͨΓ͕ऑ͍ʣ
  4. 5.

    Subscriber protocol protocol Subscriber { associatedtype Input associatedtype Failure: Error

    } protocol Publisher { func subscribe<S : Subscriber>(_ subscriber: S) where Output == S.Input, Failure == S.Failure } • subscribe ʹ੩తܕνΣοΫ͕͋Δ
  5. 6.

    Just / Sequence / ... • enum Publishers ʹఆٛࡁΈͷ Publisher

    ͕͋Δ • Publishers.Empty • Publishers.Fail • Publishers.Just • Publishers.Sequence • ͳͲ
  6. 8.

    Operators • Publisher ͕֤छͷ Operator Λ࣋ͭ • map / flatMap

    / filter / ... • combineLatest / merge / zip / ... • catch / retry / ... • debounce / delay / ..
  7. 9.

    tryMap • tryMap / tryFilter / ... • ΤϥʔΛ throw

    ͨ͠৔߹ʹ Publisher ͷΤϥʔग़ྗʹ ͯ͘͠ΕΔ .tryMap { data in let decoder = JSONDecoder() try decoder.decode(Hoge.self, from: data) }
  8. 12.

    BindableObject protocol protocol BindableObject { associatedtype PublisherType : Publisher where

    PublisherType.Failure == Never var didChange: PublisherType { get } }
  9. 13.

    BindableObject Λ࡞Δ class Hoge : BindableObject { let didChange =

    PassthroughSubject<Void, Never>() var value: String { didSet { didChange.send() } } }
  10. 14.

    SwiftUI ͱͷ bind struct HogeView : View { @ObjectBinding var

    model: Hoge var body: some View { Text($model.value) } } HogeView(model: hogeInstance)
  11. 15.

    @ObjectBinding • Swift ͷ Property Delegate ػೳʢProperty Wrapper ͱ΋ݺ͹Ε͍ͯΔʣ •

    SwiftUI Ͱ͸ଞʹ @Binding ΍ @State ͕͋Δ • BindableObject Λ౉͢ͱɺࣗಈతʹ didChange Λ؂ࢹ͠ ͯ஋Λߋ৽ͯ͘͠ΕΔ
  12. 16.

    Combine + SwiftUI ͷະདྷ • MVC ͔Βͷ୤٫ • ViewController ΍

    Storyboard ͔Βͷ୤٫ • Flux ͱ૬ੑ͕ྑ͍ʁ • Action : Publisher • State ͔Β View ΁ͷ൓ө : ObjectBinding