Elm Language Making complex update functions with ccapndave/elm-update-extra Chaining messages with andThen


Example

The andThen function allows update call composition. Can be used with the pipeline operator (|>) to chain updates.

Example: You are making a document editor, and you want that each modification message you send to your document, you also save it:

import Update.Extra exposing (andThen)
import Update.Extra.Infix exposing (..)

-- type alias Model = [...]

type Message
    = ModifyDocumentWithSomeSettings
    | ModifyDocumentWithOtherSettings
    | SaveDocument

update : Model -> Message -> (Model, Cmd)
update model msg =
    case msg of
        ModifyDocumentWithSomeSettings ->
            -- make the modifications
            (modifiedModel, Cmd.none)
            |> andThen SaveDocument
        ModifyDocumentWithOtherSettings ->
            -- make other modifications
            (modifiedModel, Cmd.none)
            |> andThen SaveDocument
        SaveDocument ->
            -- save document code

If you import also Update.Extra.Infix exposing (..) you may be able to use the infix operator:

update : Model -> Message -> (Model, Cmd)
update model msg =
    case msg of
        ModifyDocumentWithSomeSettings ->
            -- make the modifications
            (modifiedModel, Cmd.none)
            :> andThen SaveDocument
        ModifyDocumentWithOtherSettings ->
            -- make other modifications
            (modifiedModel, Cmd.none)
            :> SaveDocument
        SaveDocument ->
            -- save document code