Redux - Brings Web Architecture to Mobile

 Kittinun Vantasin

Me

github.com/kittinunf

Why do we need yet another architecture?

Programming is all about ABSTRACTION

State?

var a = 0  //storing value

a = 5 // changing value assign to sth

a += 7 // mutating value to another

a // a = 12

You touch state all the time!

Variable is a sort of state

Abstraction

struct Car {
    let make: String
    let model: String
    var numberOfWheels: Int = 4
    
    init(make: String, model: String) {
    } 
}

Car(make: "Honda", model: "HRV")

State is easy

But maintaining it is really HARD!

State is everywhere, mutating all the time

State is complex

class UIView {

   var userInteractionEnabled: Bool // 2^1

   var opaque: Bool // 2^2

   var hidden: Bool // 2^3

   var autoresizesSubviews: Bool // 2^4

}

Possibilities go exponentially

But could we avoid state?

Then, we need the best possible way to maintain state

NO, we couldn't ...

Introducing Redux?

Redux attempts to make state mutations predictable

Redux is a framework for managing state of application

By Dan Abramov - Inventor of Redux

3 Principles of Redux 

State is read-only

Single source of truth

Changes are made only with pure functions

Actions

Payload of information from app to your Store

protocol ActionType {
  init()
}

protocol StandardAction : ActionType {
  var type: String { get }
  var payload: Any? { get }
}

Reducer

Function that explains how you react to your State when Action happened

typealias Reducer = (State, ActionType) -> State

func reducer(state: State? = nil, 
             action: ActionType) -> State {
  //do something with state
  return //new state
}

Store

Object that glues everything together, responsibilities of Store are;

Hold app state

Allow access state

Allow action to be dispatched

Register listeners and also unregister

Store

protocol DisposableType {
  var dispose: () -> () { get }
}

protocol StoreType {
  associatedtype State
  
  var getState: () -> State { get }
  var dispatch: ActionType -> ActionType { get }
  var subscribe: (State -> ()) -> 
                  DisposableType { get }
}

The Flow - Unidirectional

The Flow - Unidirectional

Tell store to dispatch action

store.dispatch(action)

Store calls reducer function, returns state

func reducer(state, action) -> newState

Store notify subscribers for state changes

store.subscribe { newState in
  print(newState)
}

Demos

Q&A

Resources

redux.js.org/index.html

reswift.github.io/ReSwift

github.com/kittinunf/ReduxPlaygroud

Made with Slides.com