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

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

USAMI Kosuke

June 12, 2019
Tweet

More Decks by USAMI Kosuke

Other Decks in Programming

Transcript

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

    • RxSwift ΍ ReactiveSwift ʹͱ͔ͬͯΘΔଘࡏ • ͨͩ͠ iOS 13 Ҏ߱Ͱ͔͠ಈ࡞͠ͳ͍
  2. Combine ͷ༻ޠ • ֓೦͸ Rx (RxSwift) ʹ͍ۙɺ༻ޠ͸ҟͳΔ Combine RxSwift Publisher

    Observable Subscriber Observer CurrentValueSubject BehaviorSubject PassthroughSubject PublishSubject
  3. Publisher protocol protocol Publisher { associatedtype Output associatedtype Failure: Error

    } • Τϥʔͷܕ͕໌ࣔతͳͷ͸ ReactiveSwift ͱಉ༷ͷར఺ • ྫ͑͹ Failure Λ Never ʹ͢Δ͜ͱͰɺΤϥʔग़ྗ͠ͳ͍ Publisher ͕ఆٛͰ͖ΔʢRxSwift ͸͜ͷ͋ͨΓ͕ऑ͍ʣ
  4. 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. Just / Sequence / ... • enum Publishers ʹఆٛࡁΈͷ Publisher

    ͕͋Δ • Publishers.Empty • Publishers.Fail • Publishers.Just • Publishers.Sequence • ͳͲ
  6. Operators • Publisher ͕֤छͷ Operator Λ࣋ͭ • map / flatMap

    / filter / ... • combineLatest / merge / zip / ... • catch / retry / ... • debounce / delay / ..
  7. tryMap • tryMap / tryFilter / ... • ΤϥʔΛ throw

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

    PublisherType.Failure == Never var didChange: PublisherType { get } }
  9. BindableObject Λ࡞Δ class Hoge : BindableObject { let didChange =

    PassthroughSubject<Void, Never>() var value: String { didSet { didChange.send() } } }
  10. SwiftUI ͱͷ bind struct HogeView : View { @ObjectBinding var

    model: Hoge var body: some View { Text($model.value) } } HogeView(model: hogeInstance)
  11. @ObjectBinding • Swift ͷ Property Delegate ػೳʢProperty Wrapper ͱ΋ݺ͹Ε͍ͯΔʣ •

    SwiftUI Ͱ͸ଞʹ @Binding ΍ @State ͕͋Δ • BindableObject Λ౉͢ͱɺࣗಈతʹ didChange Λ؂ࢹ͠ ͯ஋Λߋ৽ͯ͘͠ΕΔ
  12. Combine + SwiftUI ͷະདྷ • MVC ͔Βͷ୤٫ • ViewController ΍

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