Slide 1

Slide 1 text

Reactive State Machine 2016/10/20 #iOSConfSG Yasuhiro Inami / @inamiy

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

Reactive Programming

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Streams of values over time

Slide 6

Slide 6 text

Swift FRP Libraries (FRP = Functional Reactive Programming) • RxSwift • ReactiveCocoa (RAC) • SwiftBond / ReactiveKit • Interstellar • ReactKit FRP constructs data-flow declaratively.

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

State Management using MVVM

Slide 12

Slide 12 text

Setting State (Data Binding) final class ViewModel { var rawValue: Value let variable: RxSwift.Variable let mutableProperty: RAC.MutableProperty } mySuperEventEmitter.on { viewModel.rawValue = $0 } observable.bindTo(viewModel.variable) // RxSwift viewModel.mutableProperty <~ signal // ReactiveCocoa

Slide 13

Slide 13 text

Getting State (Data Observing) final class ViewModel { var rawValue: Value let variable: RxSwift.Variable let mutableProperty: RAC.MutableProperty } // `viewModel.rawValue` is not observableʂ (if not KVO) viewModel.variable.asObservable().doOn {...} // RxSwift viewModel.mutableProperty.signal.on {...} // ReactiveCocoa

Slide 14

Slide 14 text

Observable or Signal ≒ EventEmitter

Slide 15

Slide 15 text

Variable or MutableProperty ≒ EventEmitter + Current Value

Slide 16

Slide 16 text

FRP + MVVM Super easy to manage states!

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

Really?

Slide 19

Slide 19 text

final class ViewModel { let variable: Variable }

Slide 20

Slide 20 text

final class ViewModel { let variable: Variable } final class ViewModel2 { let variable: Variable }

Slide 21

Slide 21 text

final class ViewModel { let variable: Variable } final class ViewModel2 { let variable: Variable } final class ViewModel3 { let variable: Variable }

Slide 22

Slide 22 text

final class ViewModel { let variable: Variable } final class ViewModel2 { let variable: Variable } final class ViewModel3 { let variable: Variable } ... final class ViewModel1000 { let variable: Variable }

Slide 23

Slide 23 text

let variable = { n in viewModel[n].variable } variable(1).asObservable() .map { ... } .bindTo(variable(2)) variable(2).variable.asObservable() .flatMap { ... } .bindTo(variable(3)) Observable.combineLatest(variable(123), variable(456)) .map { ... } .bindTo(variable(789)) ...

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

1000 ViewModels Much states So universe

Slide 28

Slide 28 text

FRP + MVVM ○ Data-flow × State Management

Slide 29

Slide 29 text

Problems in FRP + MVVM (1) // UI binding using RxSwift viewModel.variable.asDriver().drive(/* UI update */) // 1. State is too easy to change at anytime. viewModel.variable.value = "!!! poops!"

Slide 30

Slide 30 text

final class ViewModel { var rawValue: T let variable: Variable } let variable and var rawValue are both mutable!

Slide 31

Slide 31 text

Problems in FRP + MVVM (2) // UI binding using RxSwift viewModel.variable.asDriver().drive(/* UI update */) // 2. Data-flow is too easy to change at anytime. let disposable = !!!Observable .bindTo(viewModel.variable) // connect disposable.dispose() // disconnect

Slide 32

Slide 32 text

Data-flow itself is a state!!!

Slide 33

Slide 33 text

FRP + MVVM ↓ State "control" is easy ↓ But, number of states are increasing...

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

Are we really "managing" the states?

Slide 36

Slide 36 text

!

Slide 37

Slide 37 text

Rapidly changing "Data-flows" Unpredictable "States"

Slide 38

Slide 38 text

Paradigm Shift 1. Fix "Data-flow" 2. Minimize "State"

Slide 39

Slide 39 text

React.js

Slide 40

Slide 40 text

React.js • JavaScript framework for stateless view management • Component: Renders view in replace of DOM • JSX: XML-like tree description • Virtual DOM: Diff-patch algorithm • Data-flow from parent to child • Not same as "Reactive Programming"

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

Problem in React.js Data-flow from child to parent is difficult

Slide 44

Slide 44 text

Redux

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

Redux • Singleton state container (Store) • Topmost component no longer needs state management • Any level of components can send Action to Store easily • Reducer: State transition using pure function • Data-flow from child to parent

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

Really?

Slide 50

Slide 50 text

Problems in Redux • Middleware V.S. Reducer • Middleware adds side-effect (IO) before passing Reducer • Q. What happens if we want to add side-effects while passing Reducer? • A. We often need coupled solution • Middleware is order-dependent

Slide 51

Slide 51 text

Problems in Redux • Asynchronous task is difficult • Use Thunk? Promise? ES6 Generator? Observable? inside Middleware? • Q. What happens if multiple Middlewares chain-react each other asynchronously??? !"!"!"! • A. ¯\_(π)_/¯ • Observable is much easier to handle async-chaining

Slide 52

Slide 52 text

Think for a better architecture

Slide 53

Slide 53 text

Look through Redux types • Action = input, State • Store = state container • Reducer = (State, Action) -> State ɹɹ= state transition function • Listener = State -> /* IO */ () = state observer • Middleware = State -> ... -> Action -> /* IO */ Any = hooks side-effects

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

State Machine • Deterministic / Non-deterministic, Finite / Infinite • Acceptor / Recognizer • Pushdown, Turing Machine, etc • Transducer • Moore Machine (1956) • Mealy Machine (1955)

Slide 56

Slide 56 text

Mealy Machine (Σ, Ω, S, s0, δ, λ)

Slide 57

Slide 57 text

Mealy Machine Finite transducer that creates "new state" and "output" from "current state" and "input".

Slide 58

Slide 58 text

Mealy Machine • Σ = Set of Inputs • Ω = Set of Outputs • S = Set of States • s0 = Initial state (s0 ∈ S) • δ = State transition function, δ: S x Σ → S • λ = Output function, λ: S x Σ → Ω

Slide 59

Slide 59 text

Redux = Mealy Machine • Action = Σ = Set of Inputs • State = S = Set of States • Store = s0 + δ = Initial state + transition function • Reducer = δ = Transition function • Listener = Ω = Set of Outputs • Middleware = λ = Output function

Slide 60

Slide 60 text

Existed since 1955

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

Let's combine Redux + FRP

Slide 63

Slide 63 text

Redux + FRP (Idea) 1. Merge Reducer and Middleware: S x Σ -> S x Ω 2. Use Optional for Reducer's return value • Avoid unnecessary dispatches for state transition failure 3. Use FRP (ReactiveCocoa) for async-chaining 4. Use SignalProducer for output type that can also send next Input

Slide 64

Slide 64 text

Reactive / Rx Automaton inamiy/ReactiveAutomaton inamiy/RxAutomaton

Slide 65

Slide 65 text

Redux ˰ ReactiveAutomaton • Store 㱺 Automaton • Action 㱺 Input • Reducer 㱺 (State, Input) -> (State, SignalProducer)? • Listener 㱺 Reply -> /* IO */ () • Middleware 㱺 !

Slide 66

Slide 66 text

Example

Slide 67

Slide 67 text

Sample code (Login flow) • State: LoggedOut, LoggingIn, LoggedIn, LoggingOut • Input: Login, LoginOK, Logout, LogoutOK, ForceLogout

Slide 68

Slide 68 text

Sample code (Login flow) // 1. switch-case pattern matching let mapping: NextMapping = { fromState, input in switch (fromState, input) { case (.loggedOut, .login): return (.loggingIn, loginOKProducer) case (.loggingIn, .loginOK): return (.loggedIn, .empty) case (.loggedIn, .logout): return (.loggingOut, logoutOKProducer) case (.loggingOut, .logoutOK): return (.loggedOut, .empty) case (.loggingIn, .forceLogout), (.loggedIn, .forceLogout): return (.loggingOut, forceLogoutOKProducer) default: return nil } }

Slide 69

Slide 69 text

Sample code (Login flow) let canForceLogout: State -> Bool = [.loggingIn, .loggedIn].contains // 2. Fancy pattern matching using Swift's custom operators let mappings: [NextMapping] = [ /* input | fromState => toState | effect */ /* ---------------------------------------------------------- */ .login | .loggedOut => .loggingIn | loginOKProducer, .loginOK | .loggingIn => .loggedIn | .empty, .logout | .loggedIn => .loggingOut | logoutOKProducer, .logoutOK | .loggingOut => .loggedOut | .empty, .forceLogout | canForceLogout => .loggingOut | forceLogoutOKProducer ]

Slide 70

Slide 70 text

Sample code (Login flow) let (inputSignal, observer) = Signal.pipe() let send = observer.sendNext let automaton = Automaton( state: .loggedOut, input: inputSignal, mapping: reduce(mappings), // combining reducers strategy: .latest ) automaton.replies.observeNext { print($0) }

Slide 71

Slide 71 text

Sample code (Login flow) expect(automaton.state.value) == .loggedIn // already logged in send(Input.logout) expect(automaton.state.value) == .loggingOut // logging out... // `logoutOKProducer` will automatically transit to "logged out" expect(automaton.state.value) == .loggedOut // already logged out send(Input.login) expect(automaton.state.value) == .loggingIn // logging in... // will transit to "logged in" shortly, but... send(Input.forceLogout) // let's force-logout!"! expect(automaton.state.value) == .loggingOut // logging out... // `forceLogoutOKProducer` will automatically transit to "logged out"

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

ReactiveAutomaton • State manager, from single tiny flag to whole app's states • Similar to Elm's architecture • Program + Effect Manager (language support) = Automaton • Model = State, Msg = Input • update : Msg -> Model -> (Model, Cmd Msg) = State transition function + Output function

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

Model View ViewModel

Slide 76

Slide 76 text

Model View ✨Automaton✨

Slide 77

Slide 77 text

Recap • "Data-flow" as the "State" • FRP + MVVM is not a silver bullet • Learn from React.js + Redux • Needs UIKit evolution (e.g. ReactNative) • Redux + FRP = Reactive State Machine • Elm is awesome (Ref: A Farewell to FRP)

Slide 78

Slide 78 text

Thanks!