Simplifying State by partially introducing unidirectional data flow in your codebase

Simplifying State by partially introducing unidirectional data flow in your codebase

Fea6d57cccac4021b6c8acbfaa468965?s=128

Benedikt Terhechte

October 13, 2017
Tweet

Transcript

  1. 1

  2. 2

  3. 3

  4. 4

  5. 5

  6. 6

  7. 7

  8. 8

  9. 9

  10. None
  11. 10

  12. 11

  13. 12

  14. 13

  15. 14

  16. None
  17. 15

  18. 16

  19. 17

  20. 18

  21. 19

  22. 20

  23. 21

  24. 22

  25. 23

  26. 24

  27. 25

  28. 26

  29. 27

  30. 28

  31. 29

  32. 30

  33. 31

  34. 32

  35. 33

  36. 34

  37. 35

  38. 36

  39. 37

  40. 38

  41. 39

  42. 40

  43. 41

  44. 42

  45. 43

  46. 44

  47. /// Model struct Cinnamon { let value: Int = 0

    } enum Event { case increase } 45
  48. /// Model struct Cinnamon { let value: Int = 0

    } enum Event { case increase } func reducer(state: Cinnamon, event: Event) -> Cinnamon { var newState = state if event == .increase { newState.value += 1 } return newState } /// UI let builder = Form(state: Cinnamon(), reducer: reducer) 46
  49. 47

  50. 48

  51. 49

  52. struct AddressBook { var contacts: [Person] var searchTerm: String var

    scrollPosition: Int } 50
  53. struct AddressBookApp { struct Data { var contacts: [Person] }

    var data: Data struct UI { var searchTerm: String var scrollPosition: Int } var ui: UI } 51
  54. 52

  55. 53

  56. 54

  57. 55

  58. 56

  59. 57

  60. 58

  61. 59

  62. 60

  63. 61

  64. 62

  65. 63

  66. 64

  67. 65

  68. private var subscribers: [String: (State)->Void] = [:] public func subscribe(_

    subscriber: @escaping (State)->Void) -> String { let token = UUID().uuidString subscribers[token] = subscriber subscriber(state) return token } 66
  69. 67

  70. protocol FormComponent { associatedtype State func setup(with state: State) func

    update(state: State) -> Void } public func subscribe<Component: FormComponent> (_ subscriber: Component) -> String where Component.State == State {... 68
  71. 69

  72. func subscribe<Type: Equatable>( path: KeyPath<Data, Type>, action: @escaping (_ oldValue:

    Type, _ newValue: Type) -> Void ) -> String struct Person { let name: String } form.subscribe(path: \Person.name) { (old, new) in ... } 70
  73. private var history: [State] = [] func apply(_ change: (inout

    State) -> Void) { states.append(state) change(&state) notifySubscribers() } func undo() { state = history.popLast() notifySubscribers() } 71
  74. 72

  75. 73

  76. 74

  77. 75

  78. 76

  79. 77

  80. 78

  81. 79

  82. 80