Pure models?

Figure out your state

Let's consider we're making a UI component that depends on one of your friends and the weather (from the server)

struct State {
  friend: User
  weather: String
}

Map over inputs to produce state changes

val friendUpdate$: Observable<State -> State> = friends$.map{ newFriend ->
  return { state -> State(newFriend, state.weather)  
}

val weatherUpdate$: Observable<State -> State> = weather$.map{ newWeather ->
  return { state -> State(state.friend, newWeather) }
}

Merge all updates

// friendUpdates$   ----f---f------f->
// weatherUpdates$  -w----w---------->
// 
// merged           -w--f-w-f------f->


let updates$: Observable<State -> State> = 
    Observable.merge(
      friendUpdates$, weatherUpdates$
    )

Scan over the updates on initial state

// input$           ----1---2------3->
// initial=0
// combine=(+)
// 
// scanned          0----1---3------6->

// input$           ----(s->s)---(s->s)------(s->s)->
// initial=s_0
// combine= t(s)
// 
// scanned          s0--s1-------s2----------s3->



let state$: Observable<State> =
    updates$.scan(initialState, { currentState, nextUpdate -> nextUpdate(curentState) })

Now you have all the state you need to render your UI

// in a nice world
state$.map{ s ->
  virtualDom(s)
}

// in our world

state$.subscribe{ state ->
  textView.setText(state.weather)
  personView.setPerson(state.friend)
}

Your model is PURE

This is actually called the Elm architecture

rediscovered by accident

Pure Models

By bkase

Pure Models

  • 1,014