Skip to content

Instantly share code, notes, and snippets.

@Chadtech
Created February 13, 2019 22:53
Show Gist options
  • Save Chadtech/c9a9d6b9ae9df7060a07034ea1d74ccf to your computer and use it in GitHub Desktop.
Save Chadtech/c9a9d6b9ae9df7060a07034ea1d74ccf to your computer and use it in GitHub Desktop.
module BigLoadingState exposing (update)
type Model
= Loading LoadingModel
| Loaded LoadedModel
type alias LoadingModel =
{ name : Maybe String
, age : Maybe Int
}
type alias LoadedModel =
{ name : String
, age : Int
}
type Msg
= ReceivedAge (Result Error Int)
| ReceivedName (Result Error String)
update : Msg -> Model -> Model
update msg model =
case model of
Loading loadingModel ->
let
newLoadingModel =
updateLoading msg loadingModel
in
case checkIfLoaded newLoadingModel of
Just loadedModel ->
Loaded loadedModel
Nothing ->
Loading newLoadingModel
Loaded loadedModel ->
Loaded loadedModel
updateLoading : Msg -> LoadingModel -> (LoadingModel, Cmd Msg)
updateLoading msg loadingModel =
case msg of
ReceivedAge (Ok age) ->
{ loadingModel | age = Just age }
ReceivedName (Ok name) ->
{ loadingModel | name = Just name }
checkIfLoaded : LoadingModel -> Maybe LoadedModel
checkIfLoaded loadingModel =
Just LoadedModel
|> andMap loadingModel.age
|> andMap loadingModel.name
andMap : Maybe a -> Maybe (a -> b) -> Maybe b
andMap maybeA maybeF =
case (maybeA, maybeF) of
(Just a, Just f) ->
Just (f a)
_ ->
Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment