Slide 1

Slide 1 text

Mercari Atte and Automaton Vu Nhat Minh / @orakaro Souzoh iOS Talk

Slide 2

Slide 2 text

Mercari Atte Scala / Swift Engineer / @orakaro

Slide 3

Slide 3 text

Mercari Atte iOS development • Full RxSwift • Aggressive use of Driver • Define input/output type for ViewModel • Composition over Inheritance • Automaton

Slide 4

Slide 4 text

State Machine variations • Finite state machine • Transition function (s, a) -> s • Mealy Machine • Transition function (s, a) -> s • Output function (s, a) -> b • Moore Machine • Transition function (s, a) -> s • Output function s -> b

Slide 5

Slide 5 text

Finite State Machine • Finite state machine • Transition function (s, a) -> s • Mealy Machine • Transition function (s, a) -> s • Output function (s, a) -> b • Moore Machine • Transition function (s, a) -> s • Output function s -> b design pattern for state machines

Slide 6

Slide 6 text

Binary Gap A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. Ex: 9 = 1001 → 2

Slide 7

Slide 7 text

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. Ex: 9 = 1001 → 2 Started Zero One Binary Gap

Slide 8

Slide 8 text

Visual Format Language class func constraints(withVisualFormat format: String, options opts: NSLayoutFormatOptions = [], metrics: [String : Any]?, views: [String : Any]) -> [NSLayoutConstraint] "H:|-15-[iconImageView(30)]-[appNameLabel]-[skipButton]-15-|"

Slide 9

Slide 9 text

Visual Format Language class func constraints(withVisualFormat format: String, options opts: NSLayoutFormatOptions = [], metrics: [String : Any]?, views: [String : Any]) -> [NSLayoutConstraint] "H:|-15-[iconImageView(30)]-[appNameLabel]-[skipButton]-15-|" Direction Start Line Number Label [ ] ( ) End

Slide 10

Slide 10 text

For a “healthy” codebase Try to avoid large if-else block Try to avoid global variables Try to write pure functions

Slide 11

Slide 11 text

Signup Flow ʁ ʁ ʁ ʁ ʁ

Slide 12

Slide 12 text

Signup Flow Signup by email Facebook login One click signup by second party app Reset Password Login by Email

Slide 13

Slide 13 text

Signup Flow

Slide 14

Slide 14 text

Signup condition

Slide 15

Slide 15 text

Facebook Login

Slide 16

Slide 16 text

Login by email

Slide 17

Slide 17 text

Signup Flow Graph Root Register Root Profile Register Start With Mercari AtteLogin Facebook Email Login Register With Mercari Confirm SMS Home PassCode Email SignUp Reset Password

Slide 18

Slide 18 text

Root Register Root Profile Register Start With Mercari AtteLogin Facebook Email Login Register With Mercari Confirm SMS Home PassCode Email SignUp Reset Password

Slide 19

Slide 19 text

Transitions is Domain knowledge and should be placed at Model layer MVC / MVP / MVVM

Slide 20

Slide 20 text

Each screen represents State

Slide 21

Slide 21 text

Transition by event Root Register Root Atte Login Start With Mercari Atte Resource Mercari Resource

Slide 22

Slide 22 text

RegistrationStateViewController protocol RegistrationStateViewController { var state: RegistrationState { get } func nextViewController(event: RegistrationEvent) -> UIViewController? } extension RegistrationStateViewController { func nextViewController(event: RegistrationEvent) -> UIViewController? { let machine = AutomatonManager.registrationMachine guard let state = machine.transition(from: state, by: event) else { return nil } switch state { //... } } Automaton

Slide 23

Slide 23 text

Define Transition struct Transition { let from: S let to: S let by: E } from to by State State Event

Slide 24

Slide 24 text

Implement State Machine class Automaton { var routes: [S: [E: S]] = [:] init(initialState: S, transitions: [Transition]) { for t in transitions { addRoute(t) } } private func addRoute(_ t: Transition) { var dict = routes[t.from] ?? [:] dict[t.by] = t.to routes[t.from] = dict } func transition(from: S, by: E) -> S? { guard let next = routes[from].flatMap({ $0[by] }) else { return nil } return next } }

Slide 25

Slide 25 text

Implement State Machine class Automaton { var routes: [S: [E: S]] = [:] init(initialState: S, transitions: [Transition]) { for t in transitions { addRoute(t) } } private func addRoute(_ t: Transition) { var dict = routes[t.from] ?? [:] dict[t.by] = t.to routes[t.from] = dict } func transition(from: S, by: E) -> S? { guard let next = routes[from].flatMap({ $0[by] }) else { return nil } return next } } use dictionary for storing transitions

Slide 26

Slide 26 text

Define State and Event enum RegistrationState { case root case registerRoot case profileRegister case startWithMercari case emailLogin case atteLogin case home } enum RegistrationEvent: Hashable { case showRegisterRoot(loginMode: RootViewController.LoginMode?) case registerWithFacebook(profile: FacebookProfile?) case startWithMercari(resource: MercariIdResource?, tokenPair: TokenPair?, showsCloseButton: Bool) case loginWithEmail(showsCancelButton: Bool) case loginWithAtte(resource: MercariIdResource?, tokenPair: TokenPair?) case loginAndShowHome(tokenPair: TokenPair?, userId: Int64, hasMercariItem: Bool) }

Slide 27

Slide 27 text

Define transition graph let registrationGraph: [Transition] = [ Transition(from: .root, to: .registerRoot, by: DefaultEvent.showRegisterRoot), Transition(from: .registerRoot, to: .profileRegister, by: DefaultEvent.registerWithFacebook), Transition(from: .registerRoot, to: .startWithMercari, by: DefaultEvent.startWithMercari), Transition(from: .registerRoot, to: .emailLogin, by: DefaultEvent.loginWithEmail), Transition(from: .registerRoot, to: .atteLogin, by: DefaultEvent.loginWithAtte), Transition(from: .registerRoot, to: .home, by: DefaultEvent.loginAndShowHome), ] let registrationMachine = Automaton( initialState: .root, transitions: registrationGraph )

Slide 28

Slide 28 text

Test for transition logic only describe("ΞϓϦىಈ࣌τʔΫϯ͕ଘࡏ͠ͳ͍") { it("ϝʔϧͰ৽نొ࿥͕Ͱ͖Δ") { self.tryRoute(events: [ DefaultEvent.showRegisterRoot, DefaultEvent.registerWithEmail, DefaultEvent.showProfileRegister, DefaultEvent.confirmSMS, DefaultEvent.loginAndShowHome ]) XCTAssert(self.currentState == .home) } } //... private func tryRoute(events: [RegistrationEvent]) { for event in events { self.currentState.map { state in self.currentState = self.machine.transition(from: state, by: event) } } }

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

still have problems

Slide 31

Slide 31 text

RegistrationStateViewController protocol RegistrationStateViewController { var state: RegistrationState { get } func nextViewController(event: RegistrationEvent) -> UIViewController? } extension RegistrationStateViewController { func nextViewController(event: RegistrationEvent) -> UIViewController? { let machine = AutomatonManager.registrationMachine guard let state = machine.transition(from: state, by: event) else { return nil } switch state { //... } } Should I create ViewController here?

Slide 32

Slide 32 text

RegistrationStateViewController switch state { case .root: return RootViewController.make(withDependency: ()) case .registerRoot: return RegisterRootViewController.make(withDependency: ()) case .profileRegister : switch event { case .registerWithFacebook(.some(let profile)): return ProfileRegisterViewController.make(withDependency: .init(facebookProfile: profile)) default: return nil } case .startWithMercari: switch event { case .startWithMercari(.some(let resource), .some(let token)): return StartWithMercariViewController.make(withDependency: .init(resource: resource, token: token)) default: return nil } case .emailLogin: return EmailLoginViewController.make(withDependency: ()) case .atteLogin: switch event { case .loginWithAtte(.some(let resource), .some(let token)): return AtteLoginViewController.make(withDependency: .init(resource: resource, token: token)) default: return nil } case .home: switch event { case .loginAndShowHome(.some(let token), let userId): return HomeViewController.make(withDependency: .init(token: token, userId: userId)) default: return nil } default: return nil } Not so much different from large if-else block

Slide 33

Slide 33 text

Define transition graph let registrationGraph: [Transition] = [ Transition(from: .root, to: .registerRoot, by: DefaultEvent.showRegisterRoot), Transition(from: .registerRoot, to: .profileRegister, by: DefaultEvent.registerWithFacebook), Transition(from: .registerRoot, to: .startWithMercari, by: DefaultEvent.startWithMercari), Transition(from: .registerRoot, to: .emailLogin, by: DefaultEvent.loginWithEmail), Transition(from: .registerRoot, to: .atteLogin, by: DefaultEvent.loginWithAtte), Transition(from: .registerRoot, to: .home, by: DefaultEvent.loginAndShowHome), ] let registrationMachine = Automaton( initialState: .root, transitions: registrationGraph ) DefaultEvent !?

Slide 34

Slide 34 text

What is DefaultEvent? • In Swift 3 we still can not use default value for associated value in enum • Proposal: SE-0155 Accepted status but not included in Swift 4 struct DefaultEvent { static let showRegisterRoot: RegistrationEvent = .showRegisterRoot() static let registerWithFacebook: RegistrationEvent = .registerWithFacebook(profile: nil) static let startWithMercari: RegistrationEvent = .startWithMercari(resource: nil, token: nil) static let loginWithEmail: RegistrationEvent = .loginWithEmail() static let loginWithAtte: RegistrationEvent = .loginWithAtte(resource: nil, token: nil) static let loginAndShowHome: RegistrationEvent = .loginAndShowHome(token: nil, userId: 0) }

Slide 35

Slide 35 text

Optional type associated value enum RegistrationEvent: Hashable { case showRegisterRoot(loginMode: RootViewController.LoginMode?) case registerWithFacebook(profile: FacebookProfile?) case startWithMercari(resource: MercariIdResource?, tokenPair: TokenPair?, showsCloseButton: Bool) case loginWithEmail(showsCancelButton: Bool) case loginWithAtte(resource: MercariIdResource?, tokenPair: TokenPair?) case loginAndShowHome(tokenPair: TokenPair?, userId: Int64, hasMercariItem: Bool) } Optional

Slide 36

Slide 36 text

Automaton + FP

Slide 37

Slide 37 text

Transition function (aka Reducer) • Finite State Machine • Transition function (s, a) -> s • Mealy Machine • Transition function (s, a) -> s • Output function (s, a) -> b • Moore Machine • Transition function (s, a) -> s • Output function s -> b

Slide 38

Slide 38 text

Transition (s, a) -> s Output (s, a) -> b Mealy Machine / Moore Machine Reducer (s, a) -> (s, b) Transition (s, a) -> s Output s -> b Reducer s -> (a -> s, b)

Slide 39

Slide 39 text

Mealy Machine vs Elm Elm Architecture fun update(state: State, action: Action): Pair Transition (s, a) -> s Output (s, a) -> b Reducer (s, a) -> (s, b)

Slide 40

Slide 40 text

Mealy Machine Reducer a -> s -> (s, b) Transition (s, a) -> s Output (s, a) -> b Reducer (s, a) -> (s, b)

Slide 41

Slide 41 text

Mealy Machine Reducer a -> s -> (s, b) Transition (s, a) -> s Output (s, a) -> b Reducer (s, a) -> (s, b) Stateful Computation !!

Slide 42

Slide 42 text

Stateful Computation A stateful computation is a function that takes some state and returns a value along with some new state: s -> (s, a) class State { private let run: (S) -> (S, A) init(f: @escaping (S) -> (S, A)) { self.run = f } func run(s: S) -> (S, A) { return self.run(s) } }

Slide 43

Slide 43 text

State Monad extension State { func map(g: @escaping (A) -> B) -> State { return State { s in let (s1, val) = self.run(s: s) return (s1, g(val)) } } func flatMap(g: @escaping (A) -> State) -> State { return State { s in let (s1, val) = self.run(s: s) return g(val).run(s: s1) } } } A stateful computation is a function that takes some state and returns a value along with some new state: s -> (s, a)

Slide 44

Slide 44 text

Monad = flatmappable type Image credit: Functors, Applicatives, And Monads In Pictures

Slide 45

Slide 45 text

Swift Monads Maybe Monad Either Monad Reader Monad Observable Monad State Monad I/O Monad … Swift Optional antitypical/Result Statically typed Dependency Injection Signal / Observable Mealy Machine

Slide 46

Slide 46 text

Mealy Machine Reducer a -> s -> (s, b) Transition (s, a) -> s Output (s, a) -> b Reducer (s, a) -> (s, b) Reducer a -> State[s, b] State Monad

Slide 47

Slide 47 text

MonadicAutomaton class MonadicAutomaton { typealias T = (A) -> State private var f : T init(f: @escaping T) { self.f = f } func transition(from: S, by: A) -> (S, B) { return f(by).run(s: from) } } Reducer A -> State[S, B] A:InputɺB: Output A = Event enumɺB = UIViewController

Slide 48

Slide 48 text

Define States and Events enum RState { case any case root case registerRoot case profileRegister case startWithMercari case emailLogin case atteLogin case home } enum REvent { case showRegisterRoot case registerWithFacebook(profile: FacebookProfile) case startWithMercari(resource: MercariIdResource, token: String) case loginWithEmail case loginWithAtte(resource: MercariIdResource, token: String) case loginAndShowHome(token: String, userId: Int64) } custom type

Slide 49

Slide 49 text

Define transition graph let transitionFunc: (REvent) -> State = { event in switch event { case .registerWithFacebook(let profile): let vc = ProfileRegisterViewController.make(withDependency: .init(facebookProfile: profile)) return State { s in let s1: RState = s == .registerRoot ? .profileRegister : .any return (s1, vc) //... } } let registrationMachine = MonadicAutomaton(f : transitionFunc) A S B A S B

Slide 50

Slide 50 text

Automaton + FRP

Slide 51

Slide 51 text

Automaton + FRP • State Machine for UI inside one screen • Use stream to represent events • ReactiveSwift • inamiy/ReactiveAutomaton • RxSwift • kzaher/RxFeedback

Slide 52

Slide 52 text

Recap • State Machine • Finite State Machine • Mealy Machine • Moore Machine • Design pattern for state management • Can use FSM for simple transitions • Mealy Machine = State Monad

Slide 53

Slide 53 text

https://github.com/orakaro/MonadicMealyMachine Twitter / Github: @orakaro Q&A